2017-07-24 114 views
0

我在我的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) 
           { 
           } 

       }) 
     } 
+0

這是[回調地獄]的一個最好的例子(https://stackoverflow.com/questions/25098066/what-the-hell-is-callback-hell-and-how-和 - 爲什麼rx-solves-it)我在一段時間看過。重新將您的數據架構變得更加平坦可能有助於調試這個和未來的問題。 – Will

+0

甜蜜的耶穌,這是很多回調! –

回答

1

至少部分解決了我的問題是在這裏:

.then(result=>{ 
    return _.each(model.dataObj,data=>{ 

你需要返回,如果一個承諾你想要下面的.then等待它的完成。目前您正在返回_.each的結果,這不是承諾(_.each不是異步),所以下一個.then只是馬上繼續。您最終確實會返回看起來像service.getResp的承諾,但您將其返回到_.each函數,該函數對此沒有任何用處。

您應該循環找到您需要的field.req,然後在循環之外返回承諾。喜歡的東西:

.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) 
}) 
+0

感謝您的線索。我會嘗試修改我的代碼以在循環之後返回一個承諾。 –