Async: Can you use async.series with async / await?

Created on 4 Nov 2017  路  11Comments  路  Source: caolan/async

Can you use async await inside the async.series function?

I did some simple experiments, but they did not work as expected.

docs question

Most helpful comment

There is some mad science planned. 馃槈

All 11 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

codeofsumit picture codeofsumit  路  4Comments

jairoGilC picture jairoGilC  路  3Comments

AaronAcerboni picture AaronAcerboni  路  3Comments

Saevon picture Saevon  路  4Comments

alexpusch picture alexpusch  路  5Comments