简体   繁体   English

JavaScript:foreach循环中的Promise链接

[英]JavaScript: Promise chaining in foreach loop

I'm new to javascript promises and am having difficulty using them with a collection of elements. 我是javascript Promise的新手,在将其与一系列元素结合使用时遇到困难。 Within the collection, I perform an operation which returns a promise. 在集合中,我执行一个返回承诺的操作。 Once the entire operation (including all the Promises in the collection) has completed, I need to perform another set of operations. 整个操作(包括集合中的所有Promises)完成后,我需要执行另一组操作。 The promises within the collection need to go in sequence. 集合中的承诺需要按顺序进行。

I have tried the following approach: 我尝试了以下方法:

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);
        });
    }

What should I return from removeConference once all the conversations in collection are removed? 删除集合中的所有conversations ,我应该从removeConference返回什么?

So this is something that nabbed me early on in understanding promises. 因此,在理解诺言的早期,这就是我的难处。 You need to get ALL of your code away from the practice of passing in a callback, and then simply using the promise to call that. 您需要将所有代码都与传递回调的做法分开,然后简单地使用promise进行调用。 Instead, to keep the continuous nature of promises, you want to just return promises to the calling function, unless your function is the one that should decide what to do afterward. 相反,为了保持promise的连续性,您只想将promise 返回给调用函数,除非您的函数是应该决定后续操作的函数。 So, your code should look something like this. 因此,您的代码应如下所示。

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);
        });
    }

I'm not 100% sure this compiles correctly, but hopefully it helps conceptually. 我不是100%肯定会正确编译,但是希望它在概念上有所帮助。 Promise.all is really the key function here - it takes an array of promises, and creates a matching "control promise" that only resolves when all of them have. Promise.all实际上是这里的关键功能-它接受一组诺言,并创建一个匹配的“控制诺言”,只有当所有诺言都有时才进行解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM