Why doesn't the function return the desired result?

  • 0
    Wrote a function that takes an array of promises and returns the first one completed. Promise.race cannot be used

    function promiseRace(promises) {
        let arr = [];
        for (let elem of promises) {
           elem
           .then(() => {
               arr.push(elem)
           })
           .catch(
                console.error()
            )
        }
        return arr[0]; //ожидаю Promise {<fulfilled>: 100}. а получаю undefined
    }


    tell me why two conditions do not pass:
    1.return the result of the first fulfilled promise
    2. should throw an error

    const firstPromise = new Promise ((resolve) = & gt;
    setTimeout (() = & gt; resolve (300), 300)
    );

    const secondPromise = new Promise ((resolve) = & gt;
    setTimeout (() = & gt; resolve (200), 200)
    );

    const thirdPromise = new Promise ((resolve) = & gt;
    setTimeout (() = & gt; resolve (100), 100)
    );

    promiseRace ([firstPromise, secondPromise, thirdPromise]); // must return the first fulfilled promise
    JavaScript Anonymous, Apr 13, 2019

  • 2 Answers
  • 0
    Anonymous

  • 0
    const firstPromise = new Promise ((resolve, reject) = & gt;

    if (false) return reject

    setTimeout (() = & gt; resolve (300), 300)



    );
    Anonymous

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