背对背JavaScript承诺执行顺序
在以下代码中:
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 之外,是否有办法这样做。 。然后()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这两种诺言将同时执行(几乎),因为这正是JavaScript的优势之一:由于其基于回调的设计,它可以启动并等待许多同步功能(以承诺的形式)并行,而无需并行需要开发人员关心复杂的线程或类似线程的内容。
如果您想拥有
asyncfunc2
等待asyncfunc1
的完成-us/doc/web/javascript/reference/global_objects/promise/then“ rel =” nofollow noreferrer”>然后asyncfunc1
。您可以轻松看到并证明,通过模拟两个需要定义时间的函数(使用SettieMout),例如:
您将在控制台输出中看到第一个函数在启动脚本后将2秒完成2秒,另一个是3秒。启动脚本(而不是在2 + 3 = 5秒之后)。
如果要制作
asyncfunc2
等待asyncfunc1
而无需然后
,则可以使用async
/等待
关键字。在我的示例中,函数之后执行 asyncfunc1 !):
execpromises
然后看起来像这样(asyncfunc2
在完成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 ofasyncFunc1
, it needs to be placed inside the then-block ofasyncFunc1
.You can easily see and proof that by simulating two functions which take a defined time (using setTimeout), for example:
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 forasyncFunc1
without the need forthen
, you can use theasync
/await
keywords.In my example, the function
execPromises
would then look like this (asyncFunc2
executed after completion ofasyncFunc1
!):