制作一个javascript函数与异步回调 [英] Making a javascript function async with callback

查看:103
本文介绍了制作一个javascript函数与异步回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

previously我有

Previously I had

 MyClass.prototype.method1 = function(data1) {
    return this.data111.push(data1);
  };

 MyClass.prototype.method2 = function(i) {
    var data = this.method1(i);
    if (data.condition1 != null) {
      data.onEvent1(this);
    }
    return $(data.element).someMethod123("data123");
  };

 MyClass.prototype.method3 = function() {
    var data1 = this.method1(this._data1);
    return this.someMethod123(step.data1);
  };

MyClass.prototype.ended = function() {
    return !!this.getState("end");
  };


MyClass.prototype.getState = function(key) {
    var value = $.cookie(key);
    this._options.afterGetState(key, value);
    return value;
  };

如何使异步使用回调函数?我想应该是这样:

How do I make async using callback functions? I guess it should be so:

 MyClass.prototype.method1 = function(data1, callback) {
    if(callback){
      callback(this.data111.push(data1));
    }
    else{
      return this.data111.push(data1);
   }
  };

 MyClass.prototype.method2 = function(i, callback) {

    var data = this.method1(i);
    if (data.condition1 != null) {
      data.onEvent1(this);
    }
    if(callback){
      callback($(data.element).someMethod123("data123"));
    }
    else{
     return $(data.element).someMethod123("data123");
    }
  };

 MyClass.prototype.method3 = function(callback) {
    var data1 = this.method1(this._data1);
     if(callback){
      callback(this.someMethod123(step.data1));
    }
    else{
       return this.someMethod123(step.data1);
    }
  };

MyClass.prototype.ended = function(callback) {
    if(callback){
       callback(!!this.getState("end", /*what should be here and what should it does?*/));
    }
  };


  MyClass.prototype.getState = function(key, callback) { 
    var oldThis = this;
    setTimeout(function(){ 
                    value = $.cookie(key);
                    callback(value, oldThis); 
                    oldThis._options.afterGetState(key, value);
                  },
              0);
  };

我确实错过了一些东西,因为我从来没有在JavaScript中使用过异步​​功能。因此,它是什么?

I definitely have missed something because I never used async functions in javascript before. So it that?

和,因为我明白,做一个功能异步,我基本上要补充一个参数是一个回调函数,摆脱收益,不应该我?

And, as I understood, to make a functions async, I basically should add one more parameter as a callback function and get rid of return, should not I?

推荐答案

只是传递回调:

MyClass.prototype.ended = function(callback) {
    this.getState("end", callback);
};

您应该在其他功能做到这一点,我会建议坚持一个接口。即无论是直接返回值(如果可能)或使用回调。

You should do this in your other functions too and I'd suggest to stick to one interface. I.e. either return the value directly (if possible) or use callbacks.

这篇关于制作一个javascript函数与异步回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆