How do I get the first element of an array from promises?

  • 0
    I always get undefined how to fix it
    function promiseRace(promises) {
        let arr = [];
        for (const elem of promises) {
            elem.then(() => {
                arr.push(elem)
            })
        }
        return arr[0]
    }
    
    
    const firstPromise = new Promise((resolve) =>
      setTimeout(() => resolve(300), 300)
    );
    
    const secondPromise = new Promise((resolve) =>
      setTimeout(() => resolve(200), 200)
    );
    
    const thirdPromise = new Promise((resolve, reject) =>
      setTimeout(() => resolve(100), 100)
    );
    
    console.log(promiseRace([firstPromise, thirdPromise, secondPromise]))
    JavaScript Anonymous, Nov 15, 2020

  • 2 Answers
  • 0
    Like this, for example:

    Anonymous

  • 0
    Because first this is done:

    function promiseRace(promises) {
    let arr = [];
    for (const elem of promises) {
    elem
    }
    return arr[0]
    }
    console.log(promiseRace([firstPromise, thirdPromise, secondPromise])) // undefined


    And then this one:

    .then(() => {
    arr.push(elem)
    })
    .then(() => {
    arr.push(elem)
    })
    .then(() => {
    arr.push(elem)
    })
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!