JavaScript:承诺在foreach循环中进行链接

时间:2016-02-27 03:08:24

标签: javascript loops typescript promise

我是javascript promises的新手,并且很难将它们与元素集合一起使用。在集合中,我执行一个返回promise的操作。一旦整个操作(包括集合中的所有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后,我应该从removeConference返回什么内容?

1 个答案:

答案 0 :(得分:0)

所以这是在理解承诺时早早抓住我的东西。你需要从传递回调的做法中获取所有代码,然后简单地使用promise来调用它。相反,为了保持promises的连续性,你只想返回 promises到调用函数,除非你的函数是应该决定接下来做什么的函数。所以,你的代码看起来应该是这样的。

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真的是这里的关键功能 - 它需要一系列的承诺,并创建一个匹配的控制承诺&#34;只有在所有人都有的情况下才能解决。