我有Promise
,但它无法正常工作,因为当我尝试使用数据时,异步调用没有完成。
我一直在寻找Promise蚂蚁模式的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);
}));
}
但是,我不知道如何修改我的Typescript代码。
由于
答案 0 :(得分:1)
此处的问题是您的setTimeout(myFunc(), 3000);
即可解决您的resolve(localChatCollection)
而无需等待之前的承诺。
您必须将所有Promise存储在一个数组中,然后在解析之前等待它们。
请注意,我不知道TypeScript,如果我对语法错误,我会让你翻译。
Promise