So I got Asked in the technical interview this question: #NodeJs, #Javascript let's say we have two weather API that has to be run parallelly.
I have not been able to find the solution to this for a long time.
So How am I Supposed to choose between the two of them?
What you are looking for is Promise.any
as it returns a single promise that fulfills as soon as any of the promises in the iterable fulfills.
Promise.race
will return the first promise resolved whether it succeeded or failed.
FOR EXAMPLE
let rejected_promise = new Promise((resolve, reject) => {
reject("Rejected Promise.....");
});
let first_resolved_promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Resolved after 1 second");
}, 1000);
});
let second_resolved_promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Resolved after 2 seconds");
}, 2000);
});
let result_1 = Promise.any([
rejected_promise,
first_resolved_promise,
second_resolved_promise,
]);
result_1.then((data) => console.log("Any's data: " + data)).catch(e => console.log(e));
let result_2 = Promise.race([
rejected_promise,
first_resolved_promise,
second_resolved_promise,
]);
result_2.then((data) => console.log("Race's data: " + data)).catch(e => console.log(e));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With