Skip to content

Instantly share code, notes, and snippets.

@JacksonTian
Last active November 24, 2016 09:02
Show Gist options
  • Save JacksonTian/5084165 to your computer and use it in GitHub Desktop.
Save JacksonTian/5084165 to your computer and use it in GitHub Desktop.
循环异步调用
var After = function (callback) {
this.index = 0;
this.counter = 0;
this.results = [];
this.callback = callback;
};
After.prototype.group = function (callback) {
var that = this;
var index = that.index;
that.index++;
return function (data) {
that.counter++;
that.results[index] = callback ? allback(data) : data;
if (that.counter >= that.index) {
that.callback(that.results);
}
};
};
@JacksonTian
Copy link
Author

var after = new After(function (list) {
  console.log(list);
});
[1, 2, 3, 4, 5, 6, 7].forEach(function (val) {
  setTimeout(after.group(), Math.random() * 100, val);
});

@JacksonTian
Copy link
Author

所以原有代码只要稍作改动就可以了:)

function foo (x, callback) {
  var after = new After(callback);
  for (i = x; i > 0; i--) {
    var obj = new RemoteObj();
    obj.rpc_call(x, after.group(function (result) {
      // 把result的结果和x的值做计算
      // ...
      // ...
      return result;
    }));
  }
}

@myst729
Copy link

myst729 commented Aug 28, 2013

14行有笔误

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment