【发布时间】:2018-06-08 12:17:42
【问题描述】:
我试图在 promise 中执行一个 for 循环但没有成功,我认为我的问题与调用 resolve 的位置有关,但我不确定
/*
* Get conversations of user
* @param user {String}
*/
function getConversations(user){
return new Promise(function(resolve, reject){
var conversations = user.Conversations
var newConversations = []
for(var conversation of conversations) {
helperGetConvo(conversation.ConversID).then(function(convo){
newConversations.push(createConversationObject({messages:[], name:convo.conversationName, users:["broulaye", "doumbia"], Id:convo.conversationID}))
}).catch(function(reason) {
console.log("failure when finding conversation 2: " + reason)
})
}
resolve(newConversations)
})
}
function helperGetConvo(convoId) {
return new Promise (function(resolve, reject){
query.findConversation(convoId).then(function(convers) {
if(convers) {
console.log("conversation was found: " + convers)
}
else {
console.log("conversation was not found: " + convers)
}
resolve(convers)
}).catch(function(reason) {
console.log("failure when finding conversation: " + reason)
})
})
}
当我像这样执行我的代码时,getConversations 函数只返回一个空数组。但是当我像这样更改 getConversations 函数时:
function getConversations(user){
return new Promise(function(resolve, reject){
var conversations = user.Conversations
var newConversations = []
for(var conversation of conversations) {
helperGetConvo(conversation.ConversID).then(function(convo){
newConversations.push(createConversationObject({messages:[], name:convo.conversationName, users:["broulaye", "doumbia"], Id:convo.conversationID}))
resolve(newConversations)
}).catch(function(reason) {
console.log("failure when finding conversation 2: " + reason)
})
}
})
}
我确实得到了一个输出,但是我相信它并没有通过整个 forloop,因为据我了解,解析工作就像一个返回语句。
请大家帮忙
【问题讨论】:
-
你必须等待 Promise 解决,看看 Promise.all。我还建议您多阅读一些有关承诺的内容,您的代码真的很混乱。