[英]How to rewrite a function using Promises.all to async and await
[英]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.