Benjamin Kovach
Benjamin Kovach

Reputation: 3260

Can I specify how to handle errors in the async javascript library?

I'm trying to sanitize inputs for an asynchronous function. Specifically, given a list of credentials for an API, I'm trying to filter out which ones are invalid by sending a test request to the API and examining the result for each one.

The problem I'm facing is this: I would like to collect the invalid keys into a single list. I would normally use the async library to execute the requests in sequence, using the series function. But, from the documentation:

If any functions in the series pass an error to its callback, no more functions are run, and callback is immediately called with the value of the error.

This isn't the desired behavior: I want to collect the errors in place of the responses (or both of them). Is this possible, using this library, without changing the way I'm interacting with the API?

Upvotes: 1

Views: 67

Answers (1)

Benjamin Kovach
Benjamin Kovach

Reputation: 3260

The solution to this problem ended up being sort of hacky, but it works fine. I had a list of credentials and an async function apiCall, which looked like this:

var apiCall = function(arg, callback){
    ...
}

and the solution was to use mapSeries from async, but flip the callback arguments, like this:

async.mapSeries(credentials, function(creds, callback){
    apiCall(creds, function(err, res){
      callback(null, err);
    });
  }, 
function(nil, errors){
    console.log(_.compact(errors));
});

where _.compact removes falsy elements from the array, getting rid of the nulls that non-error responses returned. This got me exactly what I was looking for.

Upvotes: 2

Related Questions