2017-08-31 55 views
0

我有兩個promise,每個都返回一個字符串數組。我用Promise.all(p1, p2)運行它們,但我很驚訝它解決的值參數是一個12k字符串數組(這將是兩個promise的返回值之一)。Promise.All promise參數

const p1 = ModelA.find() 
    .then((bandProfiles) => { 
    const bandProfilePlayerTags = [] 
    // [...] Filling this array with strings 
    return bandProfilePlayerTags 
    }) 

const p2 = ModelB.find() 
    .then((response) => { 
    const playerTags = [] 
    // [...] Filling this array with strings 
    return playerTags 
    }) 

Promise.all(p1, p2).then((values) => { 
    // Values is an array containing more than 12k strings 
}) 

我預計值是長度爲2 values[0]的數組是從承諾1和values[1]返回的數組從承諾2.返回數組缺少什麼我在這裏?

+0

哦,上帝,我用來構建promiseArray並將其作爲參數傳遞。多麼愚蠢的錯誤,謝謝指出。 – kentor

回答

5

儘量使P1和P2在一個陣列等

const p1 = ModelA.find() 
    .then((bandProfiles) => { 
    const bandProfilePlayerTags = [] 
    // [...] Filling this array with strings 
    return bandProfilePlayerTags 
    }) 

const p2 = ModelB.find() 
    .then((response) => { 
    const playerTags = [] 
    // [...] Filling this array with strings 
    return playerTags 
    }) 

Promise.all([p1, p2]).then((values) => { 
    // Values is an array containing more than 12k strings 
}) 

Promise.all(迭代);期望一個可迭代的對象作爲參數

4

您沒有將12k字符串數組傳遞給(承諾)到Promise.all,而不是兩個承諾數組。你會想要使用

Promise.all([p1, p2]).then(values => …) 
//  ^ ^