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

时间:2015-07-22 20:37:23

标签: javascript meteor

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

这是我的代码

_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
  },

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

  

我想在每个方法完成后调用一个方法。

我认为你的意思是在所有请求完成之后。

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

_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&#39; .when()和Underscore after()无需手动设置计数器变量即可完成此操作。