async等待问题promis



我的函数问候是有效的,但当我试图返回一个承诺,一旦完成就执行它时,我一无所获,我缺少什么?我试过放return resolve((来确保函数结束,但仍然没有,我无法执行.then((。

const greetingDivs = [firstDiv, secondDiv, thirdDiv, fourthDiv, fifthDiv]
let y = 0
function greetings() {
return new Promise((resolve, reject) => {
if (y == greetingDivs.length) {
// console.log('resolved')
resolve('done')
}
if (y != greetingDivs.length) {
setTimeout(() => {
let lastDiv = consoleOutput.appendChild(greetingDivs[y])
.scrollIntoView(false, { behavior: 'smooth' })
y++
greetings()
}, 300)
}
})
}
greetings().then(() => {
console.log('hello')
})

您的代码只解析一个promise,而它创建了5个。值得注意的是,第一个,即greetings()返回的那个,永远不会解析。

我建议承诺setTimeout,这样您就可以一劳永逸地使用该逻辑。然后可以在具有for循环和await:的async函数中进行循环

const consoleOutput = document.body;
const [firstDiv, secondDiv, thirdDiv, fourthDiv, fifthDiv] = [
"Hello", "Welcome to this demo", "Hope it suits your case", "Test it", "and enjoy"].map(s => {
const div = document.createElement("div");
div.textContent = s;
return div;
});
const greetingDivs = [firstDiv, secondDiv, thirdDiv, fourthDiv, fifthDiv];
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function greetings() {
for (let div of greetingDivs) {
consoleOutput.appendChild(div)
.scrollIntoView(false, { behavior: 'smooth' });
await delay(300);
}
}
greetings().then(() => {
console.log('hello');
});

有关如何创建此类循环的更多想法,请参阅ES6-promisefor循环。

最新更新