[英]Promise chain not getting executing properly
我的nodejs代碼中有一個promise鏈,我不明白為什么要在第一個“ then”部分完成執行之前執行第二個“ then”部分。 有人可以幫助我了解以下代碼有什么問題嗎?
.then(model=>{
return mongooseModel.find({})
.then(result=>{
return _.each(model.dataObj,data=>{
return _.each(data.fields,field=>{
if(_findIndex(result, {'field.type':'xxx'})>0)
{
return service.getResp(field.req) //this is a service that calls a $http.post
.then((resp)=>{
field.resp=resp;
return field;
})
}
})
})
})
.then(finalResult=>{
submit(finalResult); //this is being called before the then above is completely done
})
})
function submit(finalResult){
.....
}
我通過進行如下更改解決了我的問題
.then(model=>{
return Promise.each(model.dataObj,data=>{
return getRequest(data.fields)
.then(()=>{
return service.getResp(field.req) //this is a service that calls a $http.post
.then((resp)=>{
field.resp=resp;
return field;
})
})
})
.then(finalResult=>{
submit(finalResult);
})
})
function getRequest(fields){
return mongooseModel.find({})
.then(result=>{
if(_findIndex(result, {'field.type':'xxx'})>0)
{
}
})
}
問題的至少一部分在這里:
.then(result=>{
return _.each(model.dataObj,data=>{
如果希望下面的.then
等待其完成.then
則需要返回一個承諾。 目前您正在返回的結果_.each
,這不是一個承諾( _.each
不是異步),所以未來.then
只是繼續的時候了。 您最終確實從service.getResp
返回了看起來像一個承諾的東西,但是您將其返回給_.each
函數,該函數沒有任何用處。
您可能應該執行循環以找到所需的field.req
,然后在循環外返回promise。 就像是:
.then(result => {
let req;
// Loop and find what you need (maybe refactor this into a function)
// _.each ...
// _.each ...
// Outside of the loops return the promise
return service.getResp(req)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.