我读到async/await
,但我有一个关键问题。
首先,我解释一个旧的例子来展示我的问题的基础,然后我问我的确切问题。
大家都知道:
console.log('1');
console.log('2');
console.log('3'); // Ex: 123
这很简单,但在以下情况下:
console.log('1');
setTimeout(()=>{
console.log('2');
},0);
console.log('3'); // Ex: 132
做法也很简单,setTimeout
函数是asynchronous
and JavaScript
从它跳转并在解析后运行它的函数,所以我们看到2
after 1
and 3
.
但是,现在我读到async/await
我写了一个这样的函数:
(async function test() {
console.log('1');
await setTimeout(()=>{
console.log('2');
},0);
console.log('3');
})(); // Ex: 132
出口是132
也是,为什么?这是我的问题,为什么3
之前运行2
?我期望因为async/await
after 1
JavaScript 等待2
然后写了3
. why 132
?
await
仅当传递给它的值是 a 时才挂起Promise
。就你而言,setTimeout
返回一个Number
所以await并不等待它。
正确的代码如下:
async function test() {
console.log('1');
await new Promise((resolve, reject) => {
setTimeout(() => {
console.log('2');
resolve()
}, 0);
});
console.log('3');
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)