那么如何将数据推送到承诺内的数组?

the*_*ter 5 javascript es6-promise

我一直在想办法。如何将结果从 Promise 循环推送到数组。任何人都可以指出我在正确的位置吗?

const ids = [1, 2, 3]
let results = []

for (let id of ids) {
    getLight(id)
        .then(light => {
            results.push(light)
        })
        .catch(err => {
            console.log(err)
        })
}
Run Code Online (Sandbox Code Playgroud)

Gre*_*reg 5

Promise 是异步的,所以你不能这样做。您可以使用Promise.allwhile 将 Promise 组合在一起,然后等待结果:

const ids = [1, 2, 3]
Promise.all(ids.map(id => getLight(id))).then(results => {
  // do something with results here
})
Run Code Online (Sandbox Code Playgroud)

分解一下:

  1. ids.map(id => getLight(id))将 ids 转换为未解决的承诺数组。

  2. Promise.all(promises).then(results => { ... })解决所有的承诺并将结果(以正确的顺序)传递给回调


mar*_*lin 5

const ids = [1, 2, 3]
let results = []

Promise.all(
  ids.map((id) =>
    getLight(id)
    .then(light => {
      results.push(light)
    })
    .catch(err => {
      console.log(err)
    })
  )).then(() => console.log(results))

function getLight(id) {
  return new Promise((res) => {
    setTimeout(res, 1000)
  }).then(() => `light for id: ${id}`)
}
Run Code Online (Sandbox Code Playgroud)

与异步/等待

(async() => {

  const ids = [1, 2, 3]
  let results = await Promise.all(
    ids.map((id) =>
      getLight(id))
  )

  console.log(results);
})()

function getLight(id) {
  return new Promise((res) => {
    setTimeout(res, 1000)
  }).then(() => `light for id: ${id}`)
}
Run Code Online (Sandbox Code Playgroud)