PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 20, 2022

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

 October 20, 2022     asynchronous, javascript, node.js     No comments   

Issue

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?


Solution

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



Answered By - Mina
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing