如何让demo()按顺序执行。
demo()
async function demo() {
doAll()
console.log("I DO NOT print sequentially");
}
async function doAll() {
var number = await getNumber();
var double = await doubleWithTimeout(number);
console.log(number,double)
}
async function getNumber() {
return new Promise(function(resolve, reject) {
var a = 2;
resolve(a);
});
}
async function doubleWithTimeout(x) {
return new Promise(function(resolve, reject) {
setTimeout(() => {
resolve(x * 2);
}, 2 );
});
}

结果:
我不按顺序打印
2 4
预期结果:
2 4
我按顺序打印
我希望我可以使用下面的代码,但你无法在承诺中等待:
async function demo() {
await doAll()
console.log("i execute without waiting");
}
async function doAll() {
return new Promise(function(resolve, reject) {
var number = await getNumber();
var double = await doubleWithTimeout(number);
console.log(number, double)
});
}
答案 0 :(得分:3)
只需使用原始代码并将await
放在doAll();
:
demo()
async function demo() {
await doAll(); // Added await here
console.log("I DO NOT print sequentially");
}
async function doAll() {
var number = await getNumber();
var double = await doubleWithTimeout(number);
console.log(number,double)
}
async function getNumber() {
return new Promise(function(resolve, reject) {
var a = 2;
resolve(a);
});
}
async function doubleWithTimeout(x) {
return new Promise(function(resolve, reject) {
setTimeout(() => {
resolve(x * 2);
}, 2 );
});
}
声明为async
的每个函数(包括doAll
)都会返回一个Promise。如果函数体返回除Promise之外的其他内容,例如返回doAll
的{{1}},则该值将由异步声明包装在一个立即解析的Promise中。
顺便说一句,你说“但你不能在承诺中等待”,这是不正确的。你不能在非异步的函数中使用await。如果要在Promise构造函数回调中使用await,只需将其声明为async:
undefined