2016-03-27 37 views
-1

爲什麼我的承諾仍處於等待狀態,我該如何解決?Javascript - 承諾保留爲待定

var foundPeopleA = findPeopleA().then(function(result) { 
     var res = [] 
     result.map(function(el) { 
      res.push(getProfileXML(el.sid)); 
     }); 
     return res 
    }); 

    var foundPeopleB = findPeopleB().then(function(result) { 
     var res = [] 
     result.map(function(el) { 
      res.push(getProfileXML(el.sid)); 
     }); 
     return res 
    }) 

    return Promise.all([findPeopleA, findPeopleB]).then(function(results) { 
     console.log(results) //[ [ Promise { <pending> }, Promise { <pending> } ], [ Promise { <pending> }, Promise { <pending> } ] ] 
    }) 

但是如果我改變的2個函數體上方進入

 var res 
     result.map(function(el) { 
      res = getProfileXML(el.sid); 
     }); 
     return res 

他們不會被掛起,我會得到的結果。

回答

1

數組不是承諾。如果你返回一組promise,then得到一組promise,就像你返回任何其他的非promise值一樣。只有當您退回承諾時,承諾纔會在then之前執行。你的foundPeopleAfoundPeopleB每個構造一個promise的數組;您需要連接這些數組並將它們傳遞給Promise.all或同等數據,以便讓它們執行。

0

嘗試將您的數組分配給映射結果。

var foundPeopleA = findPeopleA().then(function(result) { 
    var res = [] 
    res = result.map(function(el) { 
     return getProfileXML(el.sid); 
    }); 
    return res 
}); 

或者,也許你可以解決諾言?

var foundPeopleA = findPeopleA().then(function(result) { 
    var res = [] 
    res = result.map(function(el) { 
     return getProfileXML(el.sid); 
    }); 
    resolve(res); 
}); 

無論哪種方式,我相信你需要通過從映射返回值來創建你的數組來創建新的數組。

+0

第一個給出相同的輸出,第二個甚至沒有達到下一個執行,不能得到輸出。 –

+0

你是什麼意思「相同的輸出」? –

+0

我在問題中提到了一個。 // [[Promise {},Promise {}],[Promise {},Promise {}]] –

1

的問題是,你單獨使用then處理他們每個人的承諾履行,並通過all傳遞的懸而未決承諾數組處理多個承諾的履行。它將所有這些結果結合在一起,從而建立新的承諾。只是使用:

Promise.all([findPeopleA(), findPeopleB()]) 
.then(function(responses) ...