2016-10-12 69 views
-1

我有一個Promise,但它不工作,因爲我想要因爲異步調用沒有完成時,我嘗試使用數據。Javascript承諾反模式

我一直在尋找here在承諾螞蟻模式,我相信這是我的修復。然而,因爲我在Javascript方面很弱,所以我正在努力實施他們的建議。如果任何人都可以提供幫助,我將不勝感激。

我的代碼:

private findLocalChatsWithLastMessageForChat(): Promise<Mongo.Collection<Chat>> { 
    let promise: Promise<Mongo.Collection<Chat>> = new Promise<Mongo.Collection<Chat>>(resolve => { 
     let localChatCollection: Mongo.Collection<Chat> = new Mongo.Collection<Chat>(null); 
     for (let i: number = 0; i < this.chatsStorageService.chats.length; i++) { 
     let chat: Chat = this.chatsStorageService.chats[i]; 
     let findLastMessageForChatPromise: Promise<Message> = this.chatsStorageService.findLastMessageForChat(chat); 
     findLastMessageForChatPromise.then((data) => { 
      let message: Message = data; 
      chat.lastMessage = message; 
      chat.lastMessageCreatedAt = message.createdAt; 
      localChatCollection.insert(chat); 
     }); 
     } 
     resolve(localChatCollection); 
    }); 
    return promise; 
    } 

正如你所看到的,許返回到調用功能,this.chatsStorageService.findLastMessageForChat承諾完成之前。

閱讀here,提供這個解決方案:

function workMyCollection(arr) { 
    return q.all(arr.map(function(item) { 
     return doSomethingAsync(item); 
    }));  
} 

不過,我不知道如何修改我的打字稿代碼。

感謝

回答

1

這裏的問題是你的resolve(localChatCollection)這是解決您的Promise無需等待前面的承諾。

您必須將所有Promise存儲在一個數組中,並在解析前等待它們。

請注意,我不知道TypeScript我讓你翻譯,如果我錯了語法。

private findLocalChatsWithLastMessageForChat(): Promise<Mongo.Collection<Chat>> { 
    let promise: Promise<Mongo.Collection<Chat>> = new Promise<Mongo.Collection<Chat>>(resolve => { 
     let localChatCollection: Mongo.Collection<Chat> = new Mongo.Collection<Chat>(null); 

     // ----------------- 
     // ARRAY OF PROMISES 
     let promises: Array<Promise> = []; 
     // ----------------- 

     for (let i: number = 0; i < this.chatsStorageService.chats.length; i++) { 
     let chat: Chat = this.chatsStorageService.chats[i]; 
     let findLastMessageForChatPromise: Promise<Message> = this.chatsStorageService.findLastMessageForChat(chat); 

     // ----------------- 
     // PUSH ALL YOUR PROMISES IN promises ARRAY 
     promises.push(findLastMessageForChatPromise); 
     // ----------------- 

     // Binding 'chat' in order to don't loose it. 
     findLastMessageForChatPromise.then(function (_chat, data) { 
      let message: Message = data; 
      _chat.lastMessage = message; 
      _chat.lastMessageCreatedAt = message.createdAt; 
      localChatCollection.insert(_chat); 
     }.bind(null, chat)); 
     } 

     // ----------------- 
     // WAIT FOR ALL PROMISES BEFORE RESOLVING 
     Promise.all(promises).then(function() {resolve(localChatCollection);}); 
     // ----------------- 

    }); 
    return promise; 
    } 
+0

謝謝。我會試一試 – Richard

+0

哼,你的聊天變量會有問題。我會更新我的回答 –

+0

完成;)'聊天'現在就可以了 –