async icon indicating copy to clipboard operation
async copied to clipboard

How to simulate a callback with Error

Open ZenStudioLab opened this issue 9 years ago • 2 comments

What version of async are you using? 2.4.1 Which environment did the issue occur in (Node version/browser version) v7.9.0 What did you do? Please include a minimal reproducable case illustrating issue. I would like to make an asynchronous function inside async.waterfall passing an Error via new Error().

const async = require('async');

async.waterfall([
    function(callback) {
	let err = new Error("An error sample");
	callback(null, err);
    },
    function(value, callback) {
	callback(null, 100);
    }
], (err, value) => {
    console.log("Code flow enters here");
    if (err) 
	console.log(err);
    else
	console.log(value);
})

What did you expect to happen? Next function is not executed, and the main callback is immediately called with the error. What was the actual result? Next function is still executed, and the main callback is eventually call with normal result.

Code flow enters here
100

ZenStudioLab avatar Jul 04 '17 02:07 ZenStudioLab

Hi @fluteguitar, thanks for the question!

callback expects the first parameter to be the error. If it is a truthy value, the next function will not be called, and the final callback will be invoked with that value as the err, as expected. Otherwise, any other parameters after it are passed to the next task.

In your code, you would just have to change the first function:

async.waterfall([
    function(callback) {
	let err = new Error("An error sample");
	callback(err);
    },
    function(value, callback) {
	callback(null, 100);
    }
], (err, value) => {
    console.log("Code flow enters here");
    if (err) 
	console.log(err);
    else
	console.log(value);
})

See the waterfall docs for more info.

hargasinski avatar Jul 04 '17 03:07 hargasinski

Thanks hargasinski. My code works now.

ZenStudioLab avatar Jul 04 '17 03:07 ZenStudioLab