Как отправить ответ в середине нескольких асинхронных вызовов в базу данных в NodeJS?

1

Необходимо прекратить функцию POST и отправить Error: something качестве ответа, без прерывания программы.

Образец 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");
    }
  })
}

Что я должен писать вместо return res.render, поэтому POST не будет работать, функция будет завершена с кодом ошибки в ответ, но без сбоя программы, чтобы позже я мог отправить больше запросов?

  • 1
    Вместо того, чтобы делать много запросов к БД, я бы просто сделал один запрос, объединив их с OR ...
  • 2
    И я надеюсь, что вы делаете проверку входных данных.
Показать ещё 8 комментариев
Теги:
ecmascript-6
express
ecmascript-2017

2 ответа

1
Лучший ответ

Вы можете использовать async-await для этого, так как он очень часто используется среди асинхронных обработчиков вызовов, таких как Promise и Generators.

Здесь пример кода:

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);
            }

        })
    });
}
0

Попробуйте использовать async.map для решения вашей проблемы. for цикла не будет работать с асинхронными функциями.

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.
    } 
);

Ещё вопросы

Сообщество Overcoder
Наверх
Меню