简体   繁体   English

我如何同步这 3 个基于 Promise 的函数?

[英]How can i synchronize these 3 promise-based functions?

How can i synchronize these 3 promise returning functions (For example in other function)?我如何同步这 3 个承诺返回函数(例如在其他函数中)? I want to get following output -> Start -> (2secs)..2..(3secs)..3..(4secs)..4 -> End.我想获得以下输出 -> 开始 -> (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/await 语法:

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.不要忘记让这些函数返回承诺。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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