Promise.All承诺参数

时间:2017-08-31 10:45:29

标签: javascript node.js promise bluebird

我有两个promises,每个都返回一个字符串数组。我使用Promise.all(p1, p2)运行它们但我很惊讶它解析为的value参数是一个12k字符串的数组(这将是两个promises'返回之一)。

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]将是来自promise 1的返回数组,values[1]是来自promise 2的返回数组。我在这里缺少什么?

2 个答案:

答案 0 :(得分: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(迭代);期望可迭代对象作为参数

答案 1 :(得分:4)

你确实将一个12k字符串数组(一个承诺)传递给Promise.all,而不是两个承诺的数组。你会想要使用

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