簡體   English   中英

如何在不使用 async/await 的情況下重寫 function?

[英]How to rewrite a function without using async/await?

我已經使用 Promise 和 async/await 來編寫 2 個函數,這些函數以 500 毫秒的延遲一個接一個地打印提供的單詞字母:

 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>

我試圖弄清楚如何在不使用async/await的情況下重寫printWord以獲得相同的結果。 我知道它應該會產生這樣的結果:

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

但是,我不知道如何重寫printWord來實現這一點。 我會很感激任何幫助。

您可以像這樣使用數組減少:

 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>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM