繁体   English   中英

背靠背 JavaScript Promises 的执行顺序

[英]Order of execution of back to back JavaScript Promises

在以下代码中:

new Promise((resolve, reject) => {
    asyncFunc1(resolve,reject);
})
    .then((result) => {
        // do then1 stuff
    })
    
    
new Promise((resolve, reject) => {
    asyncFunc2(resolve,reject);
})
    .then((result) => {
        // do then2 stuff
    })

asyncFunc1()的 .then( .then()会在asyncFunc2()执行之前完成吗?

还是两者都会(几乎)同时执行,并且它们的then()仅在它们碰巧返回时执行?

如果第二个不等待第一个,除了将asyncFunc2()移动到asyncFunc1()的 .then .then() ) 之外,还有其他方法吗?

两个 Promise 将(几乎)同时执行,因为这正是 Javascript 的优势之一:由于其基于回调的设计,它可以并行启动并等待许多异步函数(以 Promise 的形式),而无需开发人员需要关心线程的复杂处理或类似的事情。

如果你想让asyncFunc2等待asyncFunc1的完成,它需要放在 asyncFunc1 的then asyncFunc1中。

通过模拟两个需要定义时间的函数(使用 setTimeout),您可以轻松地看到并证明这一点,例如:

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved at ' + new Date().toISOString());
    }, 2000);
  });
}

function resolveAfter3Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved at ' + new Date().toISOString());
    }, 3000);
  });
}

function execPromises() {
  console.log('calling at '  + new Date().toISOString());
  resolveAfter2Seconds().then(result => console.log(result));
  resolveAfter3Seconds().then(result => console.log(result));
}

execPromises();

您将在控制台输出中看到,第一个将在启动脚本 2 秒后完成,另一个在启动脚本 3 秒后完成(而不是在 2 + 3 = 5 秒后)。

如果你想让asyncFunc2等待asyncFunc1而不需要then ,你可以使用async / await关键字。

在我的示例中,函数execPromises将如下所示( asyncFunc2asyncFunc1完成后执行!):

async function execPromises() {
  console.log('calling at '  + new Date().toISOString());
  const resultA = await resolveAfter2Seconds();
  console.log(resultA);
  const resultB = await resolveAfter3Seconds();
  console.log(resultB);
}

暂无
暂无

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

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