Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add multiple await call inside a single try block in Javascript?

async function(req, res) {
    try {
        const user = await userCtrl.getUser();
        const userMaps = await mapsCtrl.findDetails(user.mapId);
        res.send(userMaps);
    } catch (error) {
        //handle error
        res.status(400).send(error)
    }

}

// user controll

function getUser() {

    return new Promise(function(resolve, reject) {
        //data base read using mysql
        req.app.get("mysqlConn").query(query, function(error, results, fields) {
            if (error) {
                reject(error);
            }
            resolve(results);
        });

    })
}

//maps controller function is also like above one.

This is the code handle part of an express get route. Sometimes the rejected code is not getting caught. I get the error returned from MySQL in 200 status code.

like image 932
Shameer S N Avatar asked Oct 10 '17 10:10

Shameer S N


1 Answers

Yes you can write multiple awaits in a single try catch block. so your catch block will receive the error if any of the above await fails. Refer this link for more information about async-await - https://javascript.info/async-await

reject() or resolve () doesn't mean the functions is terminated. So we have to explicitly return from the function to avoid further code execution. In your case put resolve in else block or just put return statement in the if block after the reject is called! Refer this link for more information:- Do I need to return after early resolve/reject?

I hope this help :) Regards.

like image 193
Viraj Shelke Avatar answered Oct 01 '22 08:10

Viraj Shelke