本质上我想知道为什么
Done
立即记录在这里,
Promise.resolve().then(new Promise(resolve, reject){
/* some logic */
resolve()
}).then(console.log("Done"));
如果以上还不够,这里还有更多详细信息:
我像这样链接
promise.resove()
,问题是第三个承诺内的document.querySelectorAll
在完成第二个承诺之前被触发,这是我不想要的。
let promise = Promise.resolve()
let leftPaneRowEle;
promise = promise.then(function () {
return new Promise((resolve, reject) => {
console.log('found at:', leftpaneindexes[0])
const en: HTMLElement = document.querySelectorAll('#extensionListTable tbody')[0] as HTMLElement
leftPaneRowEle = en.children[leftpaneindexes[0]]
resolve()
})
})
promise = promise.then(function () {
return new Promise((resolve, reject) => {
setTimeout(function () {
leftPaneRowEle.scrollIntoView()
leftPaneRowEle.children[0].click()
//do something more
resolve()
}, 4000)
})
})
promise = promise.then(function (en:HTMLElement) {
return new Promise((resolve, reject) => {
console.log('found at:', leftpaneindexes[1])
const en: HTMLElement = document.querySelectorAll('#extensionListTable tbody')[0] as HTMLElement
leftPaneRowEle = en.children[leftpaneindexes[1]]
resolve()
})
})
编辑:
现在我将代码修改为这样,第一个 DOM 上的所有操作都按顺序且顺利地发生,但现在第二个元素根本没有被触发,为什么会这样?
resolve()
两者都存在。不是吗?
const f = (leftPaneRowEle,index) => {
return new Promise((resolve, reject) => {
leftPaneRowEle.scrollIntoView()
leftPaneRowEle.children[0].click()
console.log('downloadBtn clicked for', leftPaneRowEle)
const port = Browser.runtime.connect()
//some more code
return () => { port.disconnect() }
resolve()
})
}
const en: HTMLElement = document.querySelectorAll('#extensionListTable tbody')[0] as HTMLElement
const leftPaneRowEle0 = en.children[leftpaneindexes[0]]
const leftPaneRowEle1 = en.children[leftpaneindexes[1]]
let promise = Promise.resolve()
promise = promise.then(f(leftPaneRowEle0,0))
promise = promise.then(f(leftPaneRowEle1,1))
我认为你应该链接 Promise 调用,这样它们将在前一个完成时按顺序执行:
let promise = Promise.resolve()
let leftPaneRowEle;
promise = promise.then(function () {
return new Promise((resolve, reject) => {
console.log('found at:', leftpaneindexes[0])
const en: HTMLElement = document.querySelectorAll('#extensionListTable tbody')[0] as HTMLElement
leftPaneRowEle = en.children[leftpaneindexes[0]]
resolve()
})
}).then(function () {
return new Promise((resolve, reject) => {
setTimeout(function () {
leftPaneRowEle.scrollIntoView()
leftPaneRowEle.children[0].click()
resolve()
}, 4000)
})
}).then(function (en:HTMLElement) {
return new Promise((resolve, reject) => {
console.log('found at:', leftpaneindexes[1])
const en: HTMLElement = document.querySelectorAll('#extensionListTable tbody')[0] as HTMLElement
leftPaneRowEle = en.children[leftpaneindexes[1]]
resolve()
})
})