[英]Javascript Promise Anti-pattern
我有一個Promise
,但它沒有按我想要的方式工作,因為當我嘗試使用數據時異步調用沒有完成。
我一直在這里查看 Promise ant-patterns,我確定這是我的解決方案。 但是,因為我在 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
承諾完成之前,承諾返回到調用函數。
在這里閱讀,提供了這個解決方案:
function workMyCollection(arr) {
return q.all(arr.map(function(item) {
return doSomethingAsync(item);
}));
}
但是,我不知道如何修改我的 Typescript 代碼。
謝謝
這里的問題是您的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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.