【发布时间】:2021-01-26 09:47:43
【问题描述】:
TL;DR
无法让async/await 函数完成async 函数通过返回自定义new Promise 对象实现的功能。
我正在尝试构建一个函数,该函数接受一个字符串,遍历字符串中的单词,并设置一个间隔,在您分配的设置间隔之后记录每个单词。完成记录后,回调将在函数完成记录每个单词后记录单词的总数。下面,你有 main 函数。
async function textReader (text, callback, interval = 1000) {
return new Promise((resolve, reject) => {
let counter = 0
let textArray = text.trim().split(' ')
let idInterval = setInterval( () => {
if(counter == textArray.length) {
callback(textArray.length)
clearInterval(idInterval)
resolve();
} else {
console.log(textArray[counter++])
}
}, interval)
})
}
然后,记录显示字数的回调:
function funCallback (wordQuantity) {
console.log(`Process complete - The text contains ${wordQuantity} words`)
}
最后,一个测试主函数的async 函数。它只是简单地运行了 3 次 main 函数,并按照应有的方式一个接一个地记录它们中的每一个。这个想法是每个await 阻塞进程,直到有一个解析值(这实际上意味着:当它在终端中记录每个单词时),一旦await 完成,跳转到下一个textReader 函数等等。
async function test () {
try {
let time = 500
await textReader('When I find myself in times of trouble ', funCallback, time)
await textReader('mother Mary comes to me ', funCallback, time)
await textReader('speaking words of wisdom Let it be', funCallback, time)
} catch (err) { console.log(err)}
}
我的问题是我希望textReader 函数能够实现相同的行为,而不必返回new Promise,而是使用await(因为我猜这就是async/await 函数应该有帮助,对吧?实现与 ES6 相同Promise)
请记住,整个计划的目标是:
- 记录特定区间内的单词
- 如果
test()拥有多个textReader(),则它们必须处于阻塞状态,这意味着一个必须等待另一个完成记录其单词,否则来自所有测试函数的单词将相互重叠- 顺便说一句,这会让人很困惑 -. - 计算每个字符串中记录了多少字。
我只是不明白如何在不从textReader() 和new Promise 返回但使用await 的情况下解决它,因为它应该在async/await 函数中。
用async/await(见下文)解决它的尝试之一没有奏效;它只是同时运行来自test() 的3 个textReader() 函数,重叠日志。
async function textReader (text, callback, time = 1000) {
let counter = 0
let textArray = text.trim().split(' ')
let loggingWords = async () => {
let idInterval = setInterval( () => {
if(counter == textArray.length) {
callback(textArray.length)
clearInterval(idInterval)
} else {
console.log(textoArray[contador++])
}
}, time)
}
let waitForLogingWords = await loggingWords()
return waitForLogingWords
};
【问题讨论】:
-
您不能将
setInterval与promise 一起使用。在awaiteddelay函数周围放置一个循环(对于setTimeout- you can't completely avoidnew Promisethere 返回new Promise)。 -
“因为我猜这就是 async/await 函数应该有帮助的,对吧?实现与 ES6 Promise 相同的功能” - 否。
async/@987654354 @ 隐藏承诺。它使它看起来没有任何承诺。它不会让承诺消失。async/await所做的一切都是由幕后的承诺提供支持的。async/await是 承诺。避免使用new Promise()本身并不会使您的代码更好,使用它本身不会使代码变得更糟。 -
您应该避免的是
callback参数。这就是为什么 Promises 首先存在的全部意义 - 将执行任务的函数与任务使用者分离。将消费者的回调传递给工作人员打破了这种范式。
标签: javascript node.js asynchronous promise async-await