0

In Documentation I can't find the way to handle error in async series method. How can i learn async js properly, usually github wiki are the below average for people who are not affiliated with it in terms of usefulness.

Here is my code:

function async1(cb,err) {
    setTimeout(function () {
        console.log(1);
        cb();
    }, 1000);
}

function async2(cb,err) {
    setTimeout(function () {
        // console.log(2);
        throw new Error;
        cb();
    }, 1000);
}

function async3(cb,err) {
    setTimeout(function () {
        console.log(3);
        cb();
    }, 1000);
}

async.series([
    async1,
    async2,
    async3
], function  (err) {
    console.log(err);
});

It just terminates and throw error.

I've few questions...

Am I handling error correctly, apparently not correctly, so what's wrong?

For Async to work does the function used in series does it have to have first parameter as callback?

If yes, then does it mean you can't use it with other libraries. Because they might not have callback as first parameter.

Muhammad Umer
  • 17,263
  • 19
  • 97
  • 168
  • 2
    Node callbacks are not throw safe and you cannot just throw exceptions this way inside them (promises for example - are by the way), you need to try/catch them and call cb with the err `cb(new Error)` instead of throwing it. See http://stackoverflow.com/questions/14301839/javascript-asynchronous-exception-handling-with-node-js – Benjamin Gruenbaum Apr 12 '15 at 20:40
  • how can i do with asyncjs – Muhammad Umer Apr 12 '15 at 21:10
  • 3
    It's not async.js fault. The bug is in setTimeout. As mentioned by Benjamin, you cannot throw an error from asynchronous functions. Instead pass the error as an argument to your callback. – slebetman Apr 12 '15 at 21:46

1 Answers1

0

Two things:

1st function only take cb parameter no err parameter so it should really be like function async1(cb){. instead of function(cb,err){. and ...

to throw error you do this

cb(new Error) //as told in comments above.

and not throw new Error.

Muhammad Umer
  • 17,263
  • 19
  • 97
  • 168