2016-02-27 55 views
0

無極鏈接我是新來的JavaScript的承諾,利用他們的元素集合時遇到了困難。在集合中,我執行返回承諾的操作。一旦整個操作(包括集合中的所有Promise)完成,我需要執行另一組操作。集合中的承諾需要按順序進行。的JavaScript:在foreach循環

我曾嘗試以下方法:

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

應該我是從removeConference什麼樣的回報,一旦所有的集合conversations被刪除?

+1

哪裏foreach循環還是我瞎 – Datsik

+0

達賽克:將編輯我的問題。 –

+0

嗨Datsik,我已經更新了這個問題。我希望現在很清楚。 –

回答

0

所以這是一件對我抓獲早在理解的承諾。你需要將所有的代碼從傳遞迴調的習慣中解放出來,然後簡單地使用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真的是這裏的關鍵功能 - 它需要承諾的陣列,並創建一個匹配的「控制承諾」當所有的人都認爲只有解決。