gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:43:31 25 4
gpt4 key购买 nike

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

这是我的代码

_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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com