Search code examples
javascriptpromisesettimeout

How can i Order the flow of execution of different promises in a correct way to get results?


Flow of the promise chain execution

Flow of the promise chain execution

const timeoutPromise = (interval, intervalName) => {
  return new Promise((resolve, reject) => {
    setTimeout(function(){
      console.log(`Executed ${intervalName} at: ${new Date().toString()} with interval of ${interval}`);
      resolve();
    }, interval);
  });
};
let main = () => {
  console.log('Starting at:', new Date().toString());

  console.log('Completed at:', new Date().toString());
};

From the above-given image, create a function that takes 2 fields as an argument: -   a letter (in our case, A, B, C, D) -   Time in milliseconds will be any distinct values provided by you

Inside the function, there must be a setTimeout with the value as above-mentioned time

The main function will start the execution such that the above-created function will be executed in the chronology specified above, i.e.: -   A & D will start together -   C will only start after completion of A & D -   B will start right after completion of A

The execution must be in such a manner that: -   Time and message should be logged in console when program execution starts -   Time and message should be logged in console when program execution ends -   Time and letter should be logged each time the function is called

I tried all the possible ways but either function A is running twice or B is logged after the program execution ends...


Solution

  • To resolve promises in a specific order, you need to chain them accordingly. Following is a breakdown of one of the ways it can be done:

    1. As A and D can start immediately, we call the timeoutPromise function and save the returned promises in variables so we can reference them later.

    2. As we need to start B as soon as A resolves, we can save a reference to the A promise in a variable so that we can start B when A completes.

    3. We can use Promise.all to wait for both A and D to resolve before we start C. The resulting promise is again stored into a variable.

    4. Promise.all is used to wait for B and C promises to settle to ensure that both promises have settled before we end the execution.

    Running example:

    const timeoutPromise = (seconds, intervalName) => {
      return new Promise((resolve, reject) => {
        setTimeout(function () {
          console.log(
            `Executed ${intervalName} at: ${new Date().toString()} with interval of ${seconds} seconds`
          );
          resolve();
        }, seconds * 1000);
      });
    };
    
    let main = () => {
      console.log('Starting at:', new Date().toString());
    
      const promiseA = timeoutPromise(1, 'A');
      const promiseAandD = Promise.all([promiseA, timeoutPromise(4, 'D')]);
    
      const promiseBThen = promiseA.then(() => timeoutPromise(1, 'B'));
      const promiseCThen = promiseAandD.then(() => timeoutPromise(1, 'C'));
    
      Promise.all([promiseCThen, promiseBThen]).then(
        () => {
          console.log('Completed at:', new Date().toString());
        }
      );
    };
    
    main();