gpt4 book ai didi

javascript - 为什么 .then() 在 promise 实际解决之前被解雇?

转载 作者:行者123 更新时间:2023-11-30 00:10:39 24 4
gpt4 key购买 nike

<分区>

我正在尝试从异步任务返回 promise ,以便我可以使用 .then() 调用使它们同步。不幸的是,我遇到了一些非常奇怪的行为。基本上,第三个 then() 在第二个解析之前执行。有人可以解释发生了什么吗?这是我的代码:

function runReleaseLoop() {
console.log('Starting release loop');
const themes = ['blue', 'red'];
return new Promise(resolve => {
buildReleases(themes, resolve);
})
}

function buildReleases(themes, onComplete) {
console.log(themes);
if (themes.length === 0) {
onComplete();
} else {
const theme = themes.pop();
Promise.resolve()
.then(setTheme(theme))
.then(someDelayedTask(theme))
.then(buildReleases(themes, onComplete));
}
}

function setTheme(theme) {
return new Promise(resolve => {
console.log(`Setting theme to ${theme}`);
resolve();
});
}

function someDelayedTask(theme) {
console.log(`Starting delayed task related to ${theme}`);
return new Promise(resolve => {
setTimeout(() => {
console.log(`Finished delayed task related to ${theme}`);
resolve();
}, 3000)
});
}

// Run the process
runReleaseLoop()
.then(() => {
console.log('Release loop finished')
});

这是我的控制台输出:

"Starting release loop"
["blue", "red"]
"Setting theme to red"
"Starting delayed task related to red"
["blue"]
"Setting theme to blue"
"Starting delayed task related to blue"
[]
"Release loop finished"
"Finished delayed task related to red"
"Finished delayed task related to blue"

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com