Javascript 在客户端上完成并行异步调用后执行操作

Javascript 在客户端上完成并行异步调用后执行操作,javascript,meteor,Javascript,Meteor,在我的客户机代码中,我并行触发多个异步请求,并希望在每个请求完成后调用一个方法 这是我的密码 _handlePostSubmit() { this._clearFailedPostingGraphs(); _.forEach(this.state.selectedGraphs, (graph) => { this.__createPosting(graph.graphType, graph._id, this.state.content, (error, re

在我的客户机代码中,我并行触发多个异步请求,并希望在每个请求完成后调用一个方法

这是我的密码

_handlePostSubmit() {
    this._clearFailedPostingGraphs();

    _.forEach(this.state.selectedGraphs, (graph) => {
      this.__createPosting(graph.graphType, graph._id, this.state.content, (error, result) => {
        if (error) {
          this._pushFailedPostingGraph(graph, error);
        } else {
          this._pushSuccesfulPostingGraph(graph);
        }
      }, this);
    }, this);
    this.props.onFetchPostings(); <------- should be called when all the 'createPosting' have completed
  },
\u handlePostSubmit(){
这是。_clearFailedPostingGraphs();
_.forEach(this.state.selectedGraphs,(图形)=>{
this.\u createPosting(graph.graphType,graph.id,this.state.content,(错误,结果)=>{
如果(错误){
此._推送失败张贴图(图,错误);
}否则{
这是一张成功的张贴图(图);
}
},这个);
},这个);
this.props.onFetchPostings();
我想在每个过程完成后调用一个方法

我猜你的意思是在所有请求都完成之后

如果是这样,请计算来自异步请求的回调,如果它们等于异步请求的数量,请执行下一步操作:

_handlePostSubmit() {
  this._clearFailedPostingGraphs();

  var expectedCallbacks = this.state.selectedGraphs.length;
  var callbackCount = 0;

  _.forEach(this.state.selectedGraphs, (graph) => {
    this.__createPosting(graph.graphType, graph._id, this.state.content, (error, result) => {
      if (error) {
        this._pushFailedPostingGraph(graph, error);
      } else {
        this._pushSuccesfulPostingGraph(graph);
      }

      callbackCount++;

      // this is what I moved -- the method you want to call after everything's done
      if (callbackCount >= expectedCallbacks) {
        this.props.onFetchPostings();
      }
    }, this);
  }, this);
},
jQuery的
.when()
和下划线的
after()
将执行此操作,而无需手动设置计数器变量