[英]JavaScript: Promise chaining in foreach loop
我是javascript Promise的新手,在将其与一系列元素结合使用时遇到困难。 在集合中,我执行一个返回承诺的操作。 整个操作(包括集合中的所有Promises)完成后,我需要执行另一组操作。 集合中的承诺需要按顺序进行。
我尝试了以下方法:
public cleanup(onCleanupComplete: any): void {
if (this._app == null) return; //this._app comes out of an external API
// Below line of code won't compile, it is just for illustration.
// I'm trying to show that I need a promise in return from method
this.removeConference(0).then(() => {
// Do additional clean up operation and call onCleanupComplete
onCleanupComplete(true, null);
});
}
private removeConference(i : number) {
if (this._app.conversationsManager.conversations == null
|| i === this.conversationLength)
return; // this.conversationLength equals initial
// number of elements in collection
// How do I return a promise here?
var conversation = this._app.conversationsManager.conversations(0);
console.log("app.cleanup.leave", `Leaving conversation ${conversation}`);
conversation.leave().then(() => {
console.log("app.cleanup.leave", `Conversation ${conversation} left successfully`);
this.app.conversationsManager.conversations.remove(conversation);
_ this.removeConference(i);
});
}
删除集合中的所有conversations
,我应该从removeConference返回什么?
因此,在理解诺言的早期,这就是我的难处。 您需要将所有代码都与传递回调的做法分开,然后简单地使用promise进行调用。 相反,为了保持promise的连续性,您只想将promise 返回给调用函数,除非您的函数是应该决定后续操作的函数。 因此,您的代码应如下所示。
public cleanup(onCleanupComplete: any):Promise<any> {
if (this._app == null) return; //this._app comes out of an external API
// Below line of code won't compile, it is just for illustration.
// I'm trying to show that I need a promise in return from method
var promiseArray = [];
for (var i = 0; i < this.conversationLength; i++) {
promiseArray.push(removeConference(i));
}
return Promise.all(promiseArray);
}
private removeConference(i : number):Promise<any> {
if (this._app.conversationsManager.conversations == null
|| i === this.conversationLength)
return Promise.resolve(true);
var conversation = this._app.conversationsManager.conversations(0);
console.log("app.cleanup.leave", `Leaving conversation ${conversation}`);
return conversation.leave().then(() => {
console.log("app.cleanup.leave", `Conversation ${conversation} left successfully`);
this.app.conversationsManager.conversations.remove(conversation);
this.removeConference(i);
});
}
我不是100%肯定会正确编译,但是希望它在概念上有所帮助。 Promise.all
实际上是这里的关键功能-它接受一组诺言,并创建一个匹配的“控制诺言”,只有当所有诺言都有时才进行解析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.