I have something like the following
var async = require(async)
function start () {
async.series(
[
function (callback) {
// do something
callback(null, "Done doing something")
return // EXIT start() NOT JUST THIS VIRTUAL FUNCTION
},
function (callback) {
// do something else if the first thing succeeded
callback(null, "Done doing something else")
}
],
function (err,result) {
if (err) {
console.log(err)
}
}
)
console.log("All done!")
}
// Start doing stuff
start()
Is it possible to exit the function start() based on some condition from within the contained virtual function where I placed the comment "EXIT start() NOT JUST THIS VIRTUAL FUNCTION"
In short yes, you can exit the task series early. async
uses error-first callbacks, which are a fundamental async callback structure in Node.js. An additional resource for learning about Async development using Node.js see this great blog post from RisingStack.
Callbacks from async
get returned to a final callback that is called when the async.series
is completed if supplied, this callback is optional. If a task within the series returns the callback with a value other than null
in the first parameter, the error parameter, the series
will break and return to the final callback handler.
async.series(
[
function (callback) {
// If some condition is met, exit series with an error
if (someCondition)
return callback('exit start', null);
return callback(null, 'Done doing something');
},
function (callback) {
if (someCondition)
return callback('error', null);
// do something else if the first thing succeeded
return callback(null, "Done doing something else")
}
],
function (err,result) {
// Handle error returned from a series callback if one occurred
if (err) {
console.log(err)
}
}
)