var async = require('async');
var workPool = async.queue(async (task, taskComplete)=>{
console.log(1, taskComplete);
async.retry(3, async (retryComplete)=>{
console.log(2, retryComplete);
// retryComplete(null, task);
});
});
workPool.push("test");
我想知道为什么我得到这个结果:
$ node test.js
1 undefined
2 undefined
https://caolan.github.io/async/
在我们接受 Node 风格的回调函数的任何地方,Async 都接受异步函数。 但是,我们不会向它们传递回调,而是使用返回值并处理任何承诺拒绝或抛出的错误。
async.mapLimit(files, async file => { // <- no callback! const text = await util.promisify(fs.readFile)(dir + file, 'utf8') const body = JSON.parse(text) // <- a parse error herre will be caught automatically if (!(await checkValidity(body))) { throw new Error(`${file} has invalid contents`) // <- this error will also be caught } return body // <- return a value! }, (err, contents) => { if (err) throw err console.log(contents) })
是的,异步不会将回调传递给async
函数——只在任务完成时返回。
那么从最终回调函数返回值呢(而不是像这个例子中那样控制台记录它们)?
在大多数情况下,来自async
函数的return
值就可以工作。
哪个async
函数正好返回一个值? 根据我的检查,它们返回无效,例如
直到
@pawelotto我认为你可以使用 node promisify util,我没有测试,但由于主回调函数签名是兼容的,我认为它会起作用。
所以上面的例子会变成(没有处理错误):
import async from "async"
import {promisify} from "util"
const promiseMapLimit = promisify(async.mapLimit)
const results = await promiseMapLimit(files, async file => { // <- no callback!
const text = await util.promisify(fs.readFile)(dir + file, 'utf8')
const body = JSON.parse(text) // <- a parse error herre will be caught automatically
if (!(await checkValidity(body))) {
throw new Error(`${file} has invalid contents`) // <- this error will also be caught
}
return body // <- return a value!
})
也许你可以试试新异步
@kazaff很酷,我不知道,谢谢!
@kazaff传奇!
@kazaff如何在 b4dnewz 的回答中使用新异步,只是无法返回结果
最有用的评论
@pawelotto我认为你可以使用 node promisify util,我没有测试,但由于主回调函数签名是兼容的,我认为它会起作用。
所以上面的例子会变成(没有处理错误):