简体   繁体   中英

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

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

You might want to try chaining to get the sequential output:

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

PS. Don't forget to make those functions return promises.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM