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

How can i synchronize these 3 promise-based functions?

如何同步这 3 个 promise 返回函数(例如在其他函数中)?我想获得以下输出 -> 开始 -> (2secs)..2..(3secs)..3..(4secs)..4 -> 结束。我试过生成器,但我的输出不是那样的(可能我做错了什么)

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

首先,将函数更改为 return 他们的承诺。例如:

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

然后将承诺链接在一起[=13​​=]

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

或使用async/await语法:

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

您可能想尝试链接以获得顺序输出:

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

PS。不要忘记对这些功能做出 return 承诺。