简体   繁体   English

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

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

I've used Promise and async/await to code 2 functions that print provided word letter after letter with 500ms delay:我已经使用 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>

I'm trying to figure out how I can rewrite printWord without using async/await to get the same result.我试图弄清楚如何在不使用async/await的情况下重写printWord以获得相同的结果。 I understand that it kind of should produce something like this:我知道它应该会产生这样的结果:

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

However, I have no idea how to rewrite printWord to achieve this.但是,我不知道如何重写printWord来实现这一点。 I'd appreciate any help.我会很感激任何帮助。

You could use array reduce like so:您可以像这样使用数组减少:

 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