Can you use async await inside the async.series function?
I did some simple experiments, but they did not work as expected.
Yes, you can! But instead of using a callback, just return a value or throw an error. http://caolan.github.io/async/global.html
Ok - please forgive me If I misunderstod something 😄 Like this?
const result = await async.each(openFiles, async (file) => {
try: {
await asyncOperation(file);
return null
} catch(err) {
return err
}
})
Since async
functions automatically convert errors into rejections, unless you wanted to do something special with the error, your example could be reduced to:
const result = await async.each(openFiles, async (file) => {
await asyncOperation(file);
})
Thank you for the improved snippet. It seems to work in a simple scenario, but in the following setting I can't get it to work:
for (const tasks of fileTasks) {
const result = await async.each(tasks, async (file) => {
await asyncOperation(file);
})
}
I was of the understanding that the for-of loop would allow asynchronous operations?
Since async.each
doesn't return a Promise, you can't await
it.
Ahh ok. So using the for-of async/await option is not a good pattern with async. Do you now if this is on the roadmap for async?
There is some mad science planned. 😉
Or util.promisify()
😉
(or pify()
)
Why does this go from a question about async.series
to async.each
?
const _async = require('async');
const _ = require('lodash');
public doSomething = async(num) : Promise<any> => {
return num*num + 1;
}
public async getResults() {
let results = new Array<any>();
let tasks = [];
try {
const list = [1,2,3,4,5,6,7,8,9,10];
list.forEach((item) => {
tasks.push((callback) => {
this.doSomething(item.then(
(res) => {
results.push(res);
callback(null, res);
}
);
})
})
results = await new Promise((resolve) => {
_async.series(tasks, (err, res) => {
console.log(res);
if (err) {
results.push(err);
}
resolve(results);
})
});
} catch (err) {
results.push(err.message);
console.log(err);
}
return _.join(results, '\r\n');
}
@aearly Hey fen could you please tell me which extracly version support async/await ?
I'm using caolan/async version 2.6.0
Most helpful comment
There is some mad science planned. 😉