Working with nested await in javascript

Viewed 851

I am implementing cache using MongoDB in-memory and MongoDB database in Nodejs application using mongoose. Here Nodejs 8.9 is used with async/await support.


let get_func = async(userId) => {

    let is_cached = await cache_user.findOne({ user_id: userId });

    if(!is_cached){
        console.log("NOT CACHIED");
        let is_dbuser = await db_user.find({});
        console.log(is_dbuser);

    } else {
        console.log("CACHED");
    }

    console.log("LEAVING get_func")
};

get_func(100);

And here's the output:

NOT CACHIED
[]
LEAVING get_func

However db_user is filled with data and was able to verify using:

db_user.find({}, function(err, users) {
   if (err) throw err;
   console.log(users);
});

Moreover checked with let is_error, is_dbuser = await db_user.find({}); if there's a doubt that function returns error and results in that order.

What's the way I should handle this nested await statement. (However it seems function is waiting for second await as expected).

1 Answers

do this instead

let get_func = async (userId) => {

    let is_cached = await cache_user.findById(userId);

    if(!is_cached){
        console.log("NOT CACHIED");
        let is_dbuser = await db_user.find({});
        console.log(is_dbuser);

    } else {
        console.log("CACHED");
    }

    console.log("LEAVING get_func")
};

get_func(100);

please take note that it makes more sense to use findById unless it doesn't satisfy your query requirements and also async may require space before the parenthesis

Related