Search code examples
javascriptasync-awaites6-promise

How can i synchronize these 3 promise-based functions?


How can i synchronize these 3 promise returning functions (For example in other function)? I want to get following output -> Start -> (2secs)..2..(3secs)..3..(4secs)..4 -> End. I've tryed Generators, but my output wasn't like that (Probably i did something wrong)

function resolveAfter2Seconds() {
  new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved 2');
      console.log('2')
    }, 2000);
  });
}
function resolveAfter3Seconds() {
  new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved 2');
      console.log('3')
    }, 3000);
  });
}
function resolveAfter4Seconds() {
 new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved 2');
      console.log('4')
    }, 4000);
  });
}

Solution

  • First, change the functions to return their promises. For example:

    function resolveAfter2Seconds() {
      return new Promise(resolve => { // <------ added return statement
        setTimeout(() => {
          resolve('resolved 2');
          console.log('2')
        }, 2000);
      });
    }
    

    Then either chain the promises together

    resolveAfter2Seconds()
      .then(() => resolveAfter3Seconds())
      .then(() => resolveAfter4Seconds());
    

    Or use async/await syntax:

    async function exampleFunction() {
      await resolveAfter2Seconds();
      await resolveAfter3Seconds();
      await resolveAfter4Seconds();
    }