为什么在我的情况下`async/await'不起作用? [英] Why `async/await` doesn't work in my case?
问题描述
我阅读了有关async/await
的信息,但我有一个关键问题.
首先,我解释一个古老的例子来说明问题的基础,然后再问确切的问题.
I read about async/await
, but I've a critical question.
At first I explain an old example to show base of my question and then I ask my exact question.
每个人都知道:
console.log('1');
console.log('2');
console.log('3'); // Ex: 123
这很简单,但在以下情况下:
It is simple but in below case:
console.log('1');
setTimeout(()=>{
console.log('2');
},0);
console.log('3'); // Ex: 132
这也很简单,setTimeout
函数是asynchronous
,而JavaScript
从其跳转并在解析运行其函数之后,因此我们看到2
在1
和3
之后.
It is simple too, setTimeout
function is asynchronous
and JavaScript
jump from it and after resolve run its function, so we see 2
after 1
and 3
.
但是,现在我读了async/await
,并编写了这样的函数:
But, now I read async/await
and I wrote a function like this:
(async function test() {
console.log('1');
await setTimeout(()=>{
console.log('2');
},0);
console.log('3');
})(); // Ex: 132
导出也是132
,为什么?这是我的问题,为什么3
在2
之前运行?我期望由于1
之后的async/await
JavaScript等待2
然后写3
.为什么132
?
The Export is 132
too, why? this is my question, why 3
run before 2
? I expect because of async/await
after 1
JavaScript wait for 2
and then wrote 3
. why 132
?
推荐答案
await
仅在传递给它的值为Promise
时挂起.对于您来说,setTimeout
返回一个Number
,所以await不会等待它.
await
only suspends when the value passed to it is a Promise
. In your case, setTimeout
returns a Number
so await doesn't wait for it.
正确的代码如下:
async function test() {
console.log('1');
await new Promise((resolve, reject) => {
setTimeout(() => {
console.log('2');
resolve()
}, 0);
});
console.log('3');
}
这篇关于为什么在我的情况下`async/await'不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!