I've a promise chain in my nodejs code, I couldn't understand why the second 'then' part is being executed before the first 'then' part completes it execution. Can someone help me understand what is wrong with the below code.
.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){
.....
}
I've solved my problem by making the the changes as below
.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)
{
}
})
}