以下代码会产生预期的输出
function toppings_choice() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(console.log("which topping would you love?"));
reject("not working");
}, 3000);
});
}
async function kitchen() {
console.log("A");
console.log("B");
console.log("C");
await toppings_choice();
console.log("D");
console.log("E");
}
kitchen();
/* Stackoverflow: show only console */
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
输出: A 乙 C 您会喜欢哪种配料? D E
但由于某种原因,以下语法中的等待不起作用
async function toppingChoice() {
setTimeout(() => {
if (true) {
return console.log("which topping would you love?");
} else {
throw "not working";
}
}, 3000);
}
async function kitchenTwo() {
console.log("A");
console.log("B");
console.log("C");
await toppingChoice();
console.log("D");
console.log("E");
}
kitchenTwo();
/* Stackoverflow: show only console */
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
输出: A 乙 C D 乙 你喜欢哪种配料?
两个函数都返回一个promise,那么为什么await关键字在第一个代码中起作用并且确实停止了代码直到promise被解决但在第二个代码中不起作用?
我需要知道是否可以使用sync/await的语法糖而不必使用promise构造函数
两个函数都返回一个承诺
不是真的,至少你的
toppingChoice
不是这样。
第一个
function toppings_choice() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(console.log("which topping would you love?"));
reject("not working");
}, 3000);
});
}
返回一个承诺,仅在超时调用其回调后才实现。
第二个
async function toppingChoice() {
setTimeout(() => {
if (true) {
return console.log("which topping would you love?");
} else {
throw "not working";
}
}, 3000);
}
不返回任何内容(没有
return
),这使得它隐式返回具有undefined
值的已履行承诺。当等待这个承诺时,它甚至不会让执行等待任何事情。调用超时回调仅过了 3000 秒。