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

Time:10-20

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?

CodePudding user response:

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));

  • Related