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");
I wonder why i got this result:
$ node test.js
1 undefined
2 undefined
https://caolan.github.io/async/
Async accepts async functions wherever we accept a Node-style callback function. However, we do not pass them a callback, and instead use the return value and handle any promise rejections or errors thrown.
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) })
Yep, Async doesn't pass callbacks to async
functions -- just return when the task is complete.
And what about returning values from the final callback function (instead of console-log them like in this example)?
Just return
ing values from async
functions works in most cases.
Which async
function exactly returns a value? From what I've checked they return void, e.g.
doUntil
@pawelotto I think for that you can use node promisify util, I didn't test but since the main callback function signature is compatible I assume it will work.
So the example above will become (without handling error):
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!
})
Maybe you can try neo-async
@kazaff cool, I didn't know about it, thanks!
@kazaff Legend!
@kazaff how to use neo-async in b4dnewz's answer, just fail to return reulst
Most helpful comment
@pawelotto I think for that you can use node promisify util, I didn't test but since the main callback function signature is compatible I assume it will work.
So the example above will become (without handling error):