【发布时间】:2016-10-12 08:16:47
【问题描述】:
我有一个Promise,但它没有按我的意愿工作,因为当我尝试使用数据时异步调用没有完成。
我一直在看 here 在 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 承诺完成之前,promise 返回到调用函数。
阅读here,提供了这个解决方案:
function workMyCollection(arr) {
return q.all(arr.map(function(item) {
return doSomethingAsync(item);
}));
}
但是,我不知道如何修改我的 Typescript 代码。
谢谢
【问题讨论】:
标签: javascript typescript promise