JavaScript: Promise chaining in foreach loop

JavaScript: Promise chaining in foreach loop

本文关键字:foreach loop in chaining Promise JavaScript      更新时间:2023-09-26

我是javascript承诺的新手,很难将它们与元素集合一起使用。 在集合中,我执行一个返回承诺的操作。完成整个操作(包括集合中的所有 Promise)后,我需要执行另一组操作。集合中的承诺需要按顺序进行。

我尝试了以下方法:

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后,我应该从删除会议返回什么?

因此,

这是让我在早期理解承诺时抓住的东西。你需要让你的所有代码远离传递回调的做法,然后简单地使用承诺来调用它。相反,为了保持承诺的连续性,你只想将承诺返回给调用函数,除非你的函数是应该决定之后做什么的函数。因此,您的代码应如下所示。

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 确实是这里的关键函数 - 它接受一系列承诺,并创建一个匹配的"控制承诺",只有在所有承诺都有时才解析。