我的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)
{
}
})
}发布于 2017-07-25 07:52:39
你的问题至少有一部分是在这里:
.then(result=>{
return _.each(model.dataObj,data=>{如果您希望下面的.then等待其完成,则需要返回承诺。目前您返回的是_.each的结果,这不是一个承诺(_.each不是异步的),所以下一个.then立即继续。您最终确实从service.getResp返回了看似promise的内容,但实际上是将其返回给_.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)
})https://stackoverflow.com/questions/45288954
复制相似问题