Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I push data to an array inside a promise then?

I've been trying to figure out. How I can push a result to an array from a promise loop. Can anyone point me in the right location?

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

for (let id of ids) {
    getLight(id)
        .then(light => {
            results.push(light)
        })
        .catch(err => {
            console.log(err)
        })
}
like image 942
themaster Avatar asked Sep 03 '18 21:09

themaster


2 Answers

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}`)
}

with async/await

(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}`)
}
like image 93
marzelin Avatar answered Sep 19 '22 18:09

marzelin


Promises are asynchronous, so you can't do that. You can use Promise.all though to compose the promises together and then wait on the result:

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

Breaking this down:

  1. ids.map(id => getLight(id)) converts the ids to an array of unresolved promises.

  2. Promise.all(promises).then(results => { ... }) resolves all the promises and passes the results (in the correct order) to the callback

like image 30
Greg Avatar answered Sep 23 '22 18:09

Greg