Search code examples
javascriptes6-promise

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

Solution

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