代码之家  ›  专栏  ›  技术社区  ›  Noob

如何在不使用async/await的情况下重写函数?

  •  0
  • Noob  · 技术社区  · 4 年前

    function injectText(value, selector) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          document.querySelector(selector).innerHTML = value
          resolve()
        }, 500)
      })
    }
    
    async function printWord(word, selector) {
      for (let i = 0; i < word.length; i++) {
        await injectText(word.substring(0, i + 1), selector)
      }
    }
    
    printWord('Hello', '.hello')
    <div class="hello"></div>

    我在想怎么重写 printWord 不使用 async/await 结果。我知道它应该产生这样的结果:

      injectText('H', '.hello')
      .then(() => {
        return injectText('He', '.hello')
      })
      .then(() => {
        return injectText('Hell', '.hello')
      })
      .then(() => {
        return injectText('Hello', '.hello')
      })
    

    然而,我不知道如何重写

    2 回复  |  直到 4 年前
        1
  •  2
  •   Jaromanda X    4 年前

    可以这样使用array reduce:

    function injectText(value, selector) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          document.querySelector(selector).innerHTML = value
          resolve()
        }, 500)
      })
    }
    
    function printWord(word, selector) {
      return word.split('') // results in an array word.length long
      .reduce((p, _, i) => 
        p.then(() => // wait for the previous promise
          injectText(word.substring(0, i + 1), selector) // do the thing and return the new promise for the next iteration
        ), 
      Promise.resolve()) // initial promise for first iteration
    }
    
    printWord('Hello', '.hello')
    <div class="hello"></div>
        2
  •  0
  •   bel3atar    4 年前

    const interval = 100 
    const word = 'Hello World !'
    word.split('').forEach((letter, index) => setTimeout(() => console.log(letter), interval * index))