在我的客户端代码中,我并行触发多个异步请求,我想在每个请求完成后调用一个方法。
这是我的代码
_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/