javascript - 为什么承诺同时执行而不是按顺序执行?
问题描述
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)
为什么程序没有按照承诺的顺序运行?我怎么解决这个问题?我已经尝试了很多次,但它们仍然一起执行,但不是按顺序执行。有人可以教我吗?很感谢。
解决方案
Yourfunction l
是一个单位函数(即不返回任何内容),因此不可等待,因为它不返回 a Promise
(显式地或通过标记为async
)。
你应该:
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
}
推荐阅读
- navbar - 更新导航栏中的路线
- ansible - gitlab-runner:找不到“本地”ansible角色
- python-3.x - Pandas:从列名中存在的子字符串列表中的现有数据框中获取新数据框
- javascript - ReactJS - 如何将具有组合状态更新的副作用的类组件转换为功能组件
- javascript - Apexcharts 在条形图中和单击时更改条形的颜色
- testing - 使用@DisplayName 描述您的类和测试方法的好的模式是什么?
- amazon-web-services - 在 AWS 的子网中检索私有 IP 地址
- java - 使用java从文本文件中删除带有不需要字符的行
- java - 以编程方式获取 KeyStore 的条目类型
- java - 无法从 JNI 中的 c++ 包装器调用 java 方法