简体   繁体   English

背靠背 JavaScript Promises 的执行顺序

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

In the following code:在以下代码中:

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

Will asyncFunc1() 's .then() complete before asyncFunc2() is executed? asyncFunc1()的 .then( .then()会在asyncFunc2()执行之前完成吗?

Or will both execute (nearly) simultaneously, and their then() s execute just whenever they happen to return?还是两者都会(几乎)同时执行,并且它们的then()仅在它们碰巧返回时执行?

If the second one does not wait for the first one, is there a way to make it do so other than moving asyncFunc2() into asyncFunc1() 's .then() ?如果第二个不等待第一个,除了将asyncFunc2()移动到asyncFunc1()的 .then .then() ) 之外,还有其他方法吗?

Both promises will execute (nearly) simultaneously, because that is exactly one of the strengths of Javascript: Due to its callback-based design, it can kick off and wait for many asynchronous functions (in the form of promises) in parallel, without the need for the developer to care about complex handling of threads or anything like that.两个 Promise 将(几乎)同时执行,因为这正是 Javascript 的优势之一:由于其基于回调的设计,它可以并行启动并等待许多异步函数(以 Promise 的形式),而无需开发人员需要关心线程的复杂处理或类似的事情。

If you want to have asyncFunc2 wait for the completion of asyncFunc1 , it needs to be placed inside the then -block of asyncFunc1 .如果你想让asyncFunc2等待asyncFunc1的完成,它需要放在 asyncFunc1 的then asyncFunc1中。

You can easily see and proof that by simulating two functions which take a defined time (using setTimeout), for example:通过模拟两个需要定义时间的函数(使用 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();

You will see in the console output that the first one will finish 2 sec after starting the script, the other one 3 sec after starting the script (and not after 2 + 3 = 5 sec).您将在控制台输出中看到,第一个将在启动脚本 2 秒后完成,另一个在启动脚本 3 秒后完成(而不是在 2 + 3 = 5 秒后)。

If you want to make asyncFunc2 wait for asyncFunc1 without the need for then , you can use the async / await keywords.如果你想让asyncFunc2等待asyncFunc1而不需要then ,你可以使用async / await关键字。

In my example, the function execPromises would then look like this ( asyncFunc2 executed after completion of asyncFunc1 !):在我的示例中,函数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