Answer the question
In order to leave comments, you need to log in
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;
}
})
);
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question