如何让 document.querySelectorAll('#selector') 等待直到解决承诺

问题描述 投票:0回答:1

我像这样链接

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()
    })
  })
javascript ecmascript-6 promise es6-promise
1个回答
-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()
    })
  })

© www.soinside.com 2019 - 2024. All rights reserved.