function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x);
}
f1();
let x = 3;
为什么会看到以下情况?
为什么JS不等待等待并向前走?能给我个建议吗?
答案 0 :(得分:2)
f1
是异步的(仅在异步上下文中 中发生等待)。因此,将执行f1(),并且由于它是异步的,因此let x = 3;
行将立即执行,而无需等待。
如果您也await
对f1()的调用,它应该可以完成您的期望。但是,为了使用await,您必须将该代码包装在另一个异步函数中,然后执行该函数。
演示(不等待):
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x);
}
f1();
let x = 3;
console.log(x);
工作版本(需要等待):
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x);
}
async function f2() {
await f1();
let x = 3;
console.log(x);
};
f2();
答案 1 :(得分:1)
更简单
(async function() {
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x);
}
await f1();
let x = 3;
console.log(x);
})();