Как разрешить предупреждения, получаемые из-за использования запроса mon goose внутри цикла / рекурсивной функции? - PullRequest
0 голосов
/ 26 марта 2020

Я делал функцию уведомления для своего проекта, в которой я должен обновить некоторые поля в коллекции уведомлений, если пользователь видел уведомление. Поэтому я отправляю ObjectIds тех уведомлений, которые видны внутри массива в теле тела через запрос post. Рад видеть, что код запущен и в базе данных mongoDB есть обновление, но я получаю некоторые предупреждения в своей консоли.

Моя функция отправки запроса: -

exports.markeNotificationRead = (req,res) => {

function asyncLoop(value){

if(value< req.body.length){
    Notification.updateOne({_id:req.body[value]}, {read: true}).then((doc) => {
        console.log(doc);

        res.setHeader("Content-Type", "application/json");
        return res.json({message: "Notification marked read"});
    })
    .catch(err => {
        console.log(err);

        return res.status(500).json(err);
    });

    asyncLoop(value + 1);

}


}
asyncLoop(0);
}

Предупреждения: -

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:485:11)
at C:\Users\XYZ\PROJECT\handlers\users.js:318:17
at processTicksAndRejections (internal/process/task_queues.js:93:5) {

код: 'ERR_HTTP_HEADERS_SENT'}

(node:25968) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:485:11)
(node:25968) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:485:11)
    at ServerResponse.header (C:\Users\XYZ\PROJECT\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\Users\XYZ\PROJECT\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Users\XYZ\PROJECT\node_modules\express\lib\response.js:267:15)
    at C:\Users\XYZ\PROJECT\handlers\users.js:324:36
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    (node:25968) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
    (node:25968) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Я также использовал foreach l oop, но все же я Я получаю то же предупреждение. Так что мне теперь делать.

...