背对背JavaScript承诺执行顺序

发布于 2025-02-13 03:20:48 字数 579 浏览 0 评论 0 原文

在以下代码中:

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()'s .then()在执行 asyncfunc2()之前完成?

还是两者都会同时执行(几乎),然后他们的然后() s在碰巧返回时执行?

如果第二个不等待第一个,除了将 asyncfunc2()移动到 asyncfunc1()'s 之外,是否有办法这样做。 。然后()

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?

Or will both execute (nearly) simultaneously, and their then()s execute just whenever they happen to return?

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()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

兔姬 2025-02-20 03:20:48

这两种诺言将同时执行(几乎),因为这正是JavaScript的优势之一:由于其基于回调的设计,它可以启动并等待许多同步功能(以承诺的形式)并行,而无需并行需要开发人员关心复杂的线程或类似线程的内容。

如果您想拥有 asyncfunc2 等待 asyncfunc1 的完成-us/doc/web/javascript/reference/global_objects/promise/then“ rel =” nofollow noreferrer”>然后 asyncfunc1

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

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秒完成2秒,另一个是3秒。启动脚本(而不是在2 + 3 = 5秒之后)。

如果要制作 asyncfunc2 等待 asyncfunc1 而无需然后,则可以使用 async /等待 关键字。

在我的示例中,函数 execpromises 然后看起来像这样( asyncfunc2 在完成之后执行 asyncfunc1 !):

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

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.

If you want to have asyncFunc2 wait for the completion of asyncFunc1, it needs to be placed inside the then-block of asyncFunc1.

You can easily see and proof that by simulating two functions which take a defined time (using setTimeout), for example:

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).

If you want to make asyncFunc2 wait for asyncFunc1 without the need for then, you can use the async/await keywords.

In my example, the function execPromises would then look like this (asyncFunc2 executed after completion of asyncFunc1!):

async function execPromises() {
  console.log('calling at '  + new Date().toISOString());
  const resultA = await resolveAfter2Seconds();
  console.log(resultA);
  const resultB = await resolveAfter3Seconds();
  console.log(resultB);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文