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

标签 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
  },

我怎样才能做到这一点?

最佳答案

and I want to call a method, after each has completed.

我假设您的意思是在所有请求 完成之后。

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

_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() 和 Underscore 的 after() 将执行此操作,您无需手动设置计数器变量。

关于javascript - 在客户端完成并行、异步调用后执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31573529/

相关文章:

Meteor React - 为什么 React Mounter 与 Kadira 的 React Layout 中的 React Components 定义不同?

javascript - Html 5 Canvas 车速度

javascript - 从文件名中删除非法字符但保留空格

macos - 通过 shell 命令停止 meteor

javascript - 如何通过 meteor 服务 HTTP 请求

meteor - 如何在 Meteor 中编写可扩展的代码

javascript - 如何返回 not found in filter function in jQuery?

javascript - 从 array.splice 返回 void

javascript - 什么是 ES2021 (ES12) 中的 WeakRef 和终结器

meteor - 如何从帐户-ui meteor 中删除用户