-1

I code Promise.all , it load about 20 lines from db when running, it stops

My code

router.get('/', (req, res) => {
  var cat = res.locals.lcCategories;

Promise.all([postModel.getTop10View(),postModel.getTop10latest()]).then(data => {
    console.log(data);
    return res.render('home');
  }).catch(next);

});

Error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (C:\Users\tranh\Desktop\Web2-News\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (C:\Users\tranh\Desktop\Web2-News\node_modules\express\lib\response.js:170:12)
    at done (C:\Users\tranh\Desktop\Web2-News\node_modules\express\lib\response.js:1004:10)
    at Immediate.<anonymous> (C:\Users\tranh\Desktop\Web2-News\node_modules\express-handlebars\lib\utils.js:26:13)
    at runCallback (timers.js:705:18)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)

enter image description here

HK boy
  • 1,398
  • 11
  • 17
  • 25
  • this might help you https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client – Afrida Anzum Jun 08 '19 at 18:52

1 Answers1

0

I had the same issue, basically this error occurs when your api as already sent a response , but due to nodejs asynchronus ability or lost cycle it again sends a response , i think that promise.all is run and the request is still sent and when the promise.all returns from its loop it again sends a request. Use await before promise.all like

await Promise.all([postModel.getTop10View(),postModel.getTop10latest()]).then(data => {
        console.log(data);
        return res.render('home');
      }).catch(next);
Ali kazmi
  • 1
  • 1