我是 JS 新手,我不明白代码片段中的行为
const task1 = new Promise((res, rej) => {
setTimeout(() => res('one'), 5000)
})
const task2 = new Promise((res, rej) => {
setTimeout(() => res('two'), 5000)
})
task1
.then((x) => { // first then
return Promise.resolve(task2)
})
.then((res) => {console.log(res)}) // expect to log after 10 seconds, but logs after 5 seconds
async function test() {
try {
const res = await task1;
const res2 = await task2;
console.log(res2); // also logs after 5 seconds
} catch (error) {
console.error(`error`);
}
}
test();
我的理解是,第一个“.then”仅在任务 1 5 秒后解决后触发,然后任务 2 启动并在另外 5 秒后解决。然而,控制台在 5 秒后记录,而不是 10 秒。我哪里出错了?
您需要在第一个 Promise 的
then
解决块中创建第二个 Promise(Promise 在创建后立即开始执行)。要修复您的代码,以便它们按承诺顺序执行:
const promiseTime=500;
const start = performance.timeOrigin + performance.now();
const task = new Promise((res, rej) => {setTimeout(() => res('one'), promiseTime);});
task
.then((x)=>{
console.log(`${x} ${(performance.timeOrigin + performance.now())-start}`);
return new Promise((res, rej) => {setTimeout(() => res('two'), promiseTime);});
})
.then((x)=>{
console.log(`${x} ${(performance.timeOrigin + performance.now())-start}`);
});
//Console output example (F12 to see):
// one 516.677001953125
// two 1033.35400390625