sawa
sawa

Reputation: 2050

async.js explanation required for understanding callback error argument

This might be an easy question, but I am writing to ask a question because I simply do not get it. What is the use of the argument 'null' in the async.some example below? According to the documentation, the parameter is supposed to take an error, but what is the point of passing an error in the callbacks?

async.some(['file1','file2','file3'], function(filePath, callback) {
fs.access(filePath, function(err) {
    callback(null, !err)
});
}, function(err, result) {
    // if result is true then at least one of the files exists
});

I did some experiments, since I do not get how the error argument arrives at main callback error parameter.

callback('err', true) // main callback returns 'err' and undefined. 
                      // second argument 'true' got lost?

callback(true) // main callback returns true and undefined.
               // did not pass error argument but still works without the first argument?

Upvotes: 0

Views: 57

Answers (1)

megawac
megawac

Reputation: 11353

Its useful to distinguish between error when a process (your some task) encounters an error and when it succeeds. When the some has completed you'll likely want to know the result and whether an error occurred and handle these cases seperately. As far as async-js is concerned any falsey value passed as an error will be considered a non-error; if an error occurs for any of the files only the error will be passed to the callback

In the code sample you provided

callback('err', true) // An error is passed so true will not be passed to final callback

callback(true) // true is the error, as an error is passed, only true (the error) and no result will be passed to the final callback.

Essentially any value which is truthy passed as the first argument to the callback will result in an immediate error

Upvotes: 2

Related Questions