我有以下不符合预期的情况:
async function sleep(milliseconds) {
await new Promise(resolve => { setTimeout(() => { resolve(); }, milliseconds)});
}
async function logMessage(message) {
await sleep(100);
console.log(message);
}
async function taskA() {
await sleep(2000);
await logMessage('In taskA');
}
async function taskB() {
await taskA().then(logMessage('In taskB'));
}
taskB();
当我调用taskB时,我希望taskA在进入then之前完成。我期待这个输出:
In taskA
In taskB
然而,实际发生的是立即调用logMessage('in taskB'),而不是在taskA完成后调用,因此输出为:
In taskB
In taskA
我在这里误解了什么?
答案 0 :(得分:1)
应为await taskA().then(()=>logMessage("In taskB"));
而不是await taskA().then(logMessage('In taskB'));
async function sleep(milliseconds) {
await new Promise(resolve => {
setTimeout(() => {
resolve();
}, milliseconds);
});
}
async function logMessage(message) {
await sleep(100);
console.log(message);
}
async function taskA() {
await sleep(2000);
await logMessage("In taskA");
}
async function taskB() {
await taskA().then(()=>logMessage("In taskB"));
}
taskB();