gpt4 book ai didi

javascript - 为什么这些 promise 是同时执行的,而不是按顺序执行的?

转载 作者:行者123 更新时间:2023-12-02 22:22:44 25 4
gpt4 key购买 nike

function page() {
return new Promise((resolve, reject) => {
setTimeout(function() {
fo = $("#root>div>div>main>div>div:nth-child(3)>div>div:nth-child(2)>div>div>div:nth-child(2)>div:nth-child(2)>div>div:nth-child(2)>div>div:nth-child(2)>div>ul>li:nth-last-child(1)")
fo.click()
console.log('翻页')
resolve();
}, 200)
})
}
function l() {
for (let i = 0, p = Promise.resolve(); i < 10; i++) {
p = p.then(() => {
return new Promise(resolve =>
setTimeout(function() {
console.log('wo')
$('#root>div>div>main>div>div:nth-child(3)>div>div:nth-child(2)>div>div>div:nth-child(2)>div:nth-child(2)>div>div:nth-child(2)>div>div:nth-child(1)>div:nth-child(1)>table>tbody>tr>td:nth-child(7)>div>div:nth-child(2)>a>span').eq(i).click()
resolve();
}, 200)
)
})
.then(() => {
return new Promise(resolve =>
setTimeout(function() {
console.log('wocao')
$('body>div:nth-last-child(1)>div>div>div:nth-child(3)>div:nth-child(2)>button>span').click()
resolve();
}, 200)
)
}
)
}
}
Promise.resolve().then(l).then(page)

为什么程序没有按照 promise 的顺序运行?我怎么解决这个问题?我已经尝试了很多次,但它们仍然一起执行,但不是按顺序执行。有人可以教我吗?非常感谢。

最佳答案

您的function l是一个单位函数(即不返回任何内容),因此不可等待,因为它不返回Promise(无论是显式返回,还是通过标记为异步)。

你应该:

function l() {
let p = Promise.resolve() // this needs to exist out of the loop scope
for (let i = 0; i < 10; i++) {
p = p.then( /* ... */ )
}
return p; // <-- so it can be returned here
}

关于javascript - 为什么这些 promise 是同时执行的,而不是按顺序执行的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59178047/

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