Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run two function parallelly and send response of fastest function?

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.

  • Condition1:The fastest one to produce the result should be sent as a response.
  • Condition2:If one Fails and the other succeeds the succeeding result should be sent as a response.

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?

like image 833
Pujan Katuwal Avatar asked Oct 17 '25 12:10

Pujan Katuwal


1 Answers

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));
like image 115
Mina Avatar answered Oct 20 '25 01:10

Mina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!