A
A
Atheist212020-09-30 11:57:09
JavaScript
Atheist21, 2020-09-30 11:57:09

Why is the result undefined?

Write a function that takes an array of promises and returns the result of the one that completed first. Moreover, if the first promise generated an error, it is necessary to return it. Moreover, the solution should not call Promise.race of the standard library.

Example:

const firstPromise = new Promise((resolve) =>
  setTimeout(() => resolve(300), 300)
);
const secondPromise = new Promise((resolve) =>
  setTimeout(() => resolve(200), 200)
);
const thirdPromise = new Promise((resolve) =>
  setTimeout(() => resolve(100), 100)
);
promiseRace([firstPromise, secondPromise, thirdPromise]); // 100


function promiseRace(promises) {
          let isResolve = false;
          [...promises].forEach((prom) =>
            prom.then((p) => {
              if (p && !isResolve) {
                isResolve = true;
                if (p instanceof Error) throw p;
                return p;
              }
            })
          );
      }

if I put console.log before return, then the console gives the correct result, and the return is undefined. I do not ask for a solution, but I want an answer to the question, why is this so?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Anton, 2020-09-30
@Atheist21

Because in the above code promiseRace, there is actually no return from. In this case, you need to rewrite something like this:
https://jsfiddle.net/e6cgyt21/
here the peculiarity is used that a Promise can be executed only once and it will be executed by the first fulfilled promise from the array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question