Search code examples
node.jsexpressasynchronousnode-async

nodejs- Best method to perform multiple async calls inside a function?


I'm creating an API using Express JS (Express 4) framework. I'm pretty new to NodeJS so I would like to know the best way to perform multiple async calls inside the same function.

For this example, I've got a function called Login in my Login Controller. Inside this function, let's say I gotta make quite a few async calls for authenticating a user, saving login info and similar functionalities like that.

But for some async calls, data to be processed should be fetched from the previous async call (they are dependent functions) and some functions are not like that.

Right now, this is how I'm doing the calls.

exports.login = function (req, res) {

    var user = {
      email: '[email protected]',
      password: 'password'
    };
    //Async call 1
    Login.authUser(user, function (err1, rows1) {
        var user_id = rows1[0].id;

        //Async call 2 (depends on async call 1 for user_id)
        Login.fetchUserDetails(user_id, function (err2, rows2) {

            //Async call 3
            Login.updateLoginInfo(param3, function (err3, rows3) {

                //Some functionality occurs here then async call 4 happens

                //Async call 4
                Login.someOtherFunctionality(param4, function (err4, rows4) {
                    //return response to user
                    res.json({
                        success: true
                    });
                });

            });
        });

    });
};

Now all these async calls are nested. Is there any other way I can do this?

P.S: I didnt add error handling in this example


Solution

  • you can use promise as well. It will make you syntax more pretty. Your code will look like

    Login.authUser(user).
    then(fetchUser).
    then(updateLoginInfo).
    then(someOtherFunctionality).
    catch(function(error){
    //log your error or whatever
    });