2

Need to terminate POST function and send Error: something as response, without terminating program.

Sample for-loop:

for (let i = 0; i < req.body.listoftouristsbyid.length; i++) {
  client.query("SELECT tourists.id FROM tourists WHERE tourists.id = " + req.body.listoftouristsbyid[i], function(err, result) {
    done();
    if (result.rows.length === 0) {
      console.log("Tourist " + req.body.listoftouristsbyid[i] + " you want to add does not exist");
      res.status(500);
      return res.render("Bad listoftoutistbyid request, student with id " + i + " does not exist");
    }
  })
}

What should I write in place of return res.render, so POST won't work, function will terminate with error code in response, but without crashing program so I can send more requests later ?

10
  • 1
    Instead of making a lot of requests to DB I would just make one query by combining them with OR ... Commented Sep 27, 2018 at 17:52
  • 2
    And I hope you do input validation. Commented Sep 27, 2018 at 17:53
  • You could use try ... catch statement. Commented Sep 27, 2018 at 17:54
  • 1
    That means that any visitor of your website might have fun with your db xkcd.com/327 Commented Sep 27, 2018 at 18:00
  • 1
    Well don't do a lot of queries in a loop and try to send a response after each of them returns. There can only be one response. Commented Sep 27, 2018 at 19:41

2 Answers 2

3

You can use async-await for this, as it's highly used among asynchronous call handlers like Promise and Generators.

Here's a sample code:

app.post('/APIendpoint', async (req, res) => {

    let listoftouristsbyid      = req.body.listoftouristsbyid;

    let dbResult = [];

    // Can put this whole for loop inside try too. Then success response will also be inside try after for-loop
    for (let i = 0; i < listoftouristsbyid.length; i++) {

        try {
            let result = await callDB( "SELECT tourists.id FROM tourists WHERE tourists.id = " + listoftouristsbyid[i] );
            dbResult.push(result);
        }
        catch (err) {

            console.log("Tourist " + listoftouristsbyid[i] + " you want to add does not exist");

            res.status(500);
            return res.send("Bad listoftoutistbyid request, student with id " + i + " does not exist");

        }
    }

    console.log("Successfully fetched all records ", dbResult);

    res.status(200);
    return res.send(dbResult);

});

function callDB(query) {

    return new Promise ( (resolve, reject) => {
        client.query(query, function(err, result) {

            if (result.rows.length === 0) {
                reject("not found");
            } else {
                resolve(result.rows);
            }

        })
    });
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try using async.map to solve your problem. for loop is not gonna work with async functions.

async.map(
    req.body.listoftouristsbyid, 
    function(touristId, callback) {
        client.query("<query>", function(err, result) {
            if (result.rows.length === 0) {
                callback(new Error("not found"));
            }
            callback(null, result);
        });
    },
    function(err, result) {
        // send response here.
    } 
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.