[英]Clarification on order of Promise resolution using Async/Await
[英]promise resolution order and await
我有這段代碼:
af = async () => { Promise.resolve() .then(x => console.log("first then")) .then(x => console.log("second then")) await Promise.resolve() console.log("after await") } af()
從<script>
運行Google Chrome 61.0.3163.91(正式版本)(64位)時,得到以下結果:
first then
after await
second then
但是,當我將代碼復制/粘貼到控制台中並運行它時,我得到了:
first then
second then
after await
node.js 8.5.0的行為類似。
正確的順序是什么,為什么會有區別?
//編輯
另一個有趣的事情是此代碼的firefox 55.0.2(64位):
af = async () => { Promise.resolve() .then(x => console.log("first then")) .then(x => console.log("second then")) .then(x => console.log("third then")) .then(x => console.log("forth then")) await Promise.resolve() console.log("after await") } af()
日志:
first then
second then
third then
after await
forth then
正確的方法是在Promise.resolve()
之前添加一個await
,該await
將執行“第一個然后是”和“第二個然后是”控制台日志。 這樣,它將等待承諾完成,然后再進入控制台日志進行“等待后”
這就是您要做的方式。
af = async () => { await Promise.resolve() // NOTE: I added a "await" before the Promise.resolve() .then(x => console.log("first then")) .then(x => console.log("second then")) await Promise.resolve() console.log("after await") } af()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.