7
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.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
Shameer S N
  • 93
  • 1
  • 8
  • 2
    `Is this ok?` Is you current code not working? If it is and you simply asking for an opinion on your implementation than I believe this question could probably be closed as **primarily opinion-based** Otherwise, if you have an issue, please post your actual code with the details of the issue. – Nope Oct 10 '17 at 10:14
  • @Fran Yes. I have some issue. Some time rejected code not going to catch block. Await functions are MySQL database read. Mysql errors are catching but always not. – Shameer S N Oct 10 '17 at 10:34
  • 1
    In that case please post the minimum required relevant actual code to create a [**Minimal, Complete, and Verifiable example**](https://stackoverflow.com/help/mcve) preferably in a working snippet to demonstrate the issue. – Nope Oct 10 '17 at 10:36
  • @Fran I will update asap – Shameer S N Oct 10 '17 at 10:37
  • How do you know there's an error when it's not caught? – Bergi Oct 10 '17 at 12:45
  • @Bergi rejected error contains error info from mysql, which simply goes to the 200 status code. By looking the response i can confirm its an error which is not going to catch block – Shameer S N Oct 10 '17 at 23:44
  • @shameersn So you say `findDetails()` fulfills with an error? If it doesn't go into the catch block, it's not a rejection. As Fran said, please provide a [mcve]. – Bergi Oct 11 '17 at 00:02

1 Answers1

5

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.

Viraj Shelke
  • 768
  • 8
  • 11