0

I'm doing some fetches in a promise and then consolidating my results into a response json. When I console.log it, it prints out as expected, but I'm not sure how to return it as the response.

I have something like this:

router.get('/', function(req, res) {
  Promise.all([ fetch(url1); fetch(url2); ]);
}.then(function(responses) {
  // Consolidate responses into one data json
  console.log(data); // Prints correct object
  return response; // This doesn't work
}
Latcie
  • 701
  • 1
  • 7
  • 21
  • You might want to return `Promise.all`. That may not fix the whole thing, but it's a start. – evolutionxbox Oct 13 '20 at 14:25
  • 1
    `res.send(data);` or `res.json(data)` – Yousaf Oct 13 '20 at 14:26
  • 1
    Please update your script with code that doesn't have syntax errors – Manuel Spigolon Oct 13 '20 at 14:26
  • That code uses a `data` variable that isn't defined anywhere in the code, and has multiple syntax errors. The correct way to do this is: `router.get('/', function(req, res) { Promise.all([ fetch(url1), fetch(url2) ]) .then(([result1, result2]) => { /* Use result1 and result2 here, for instance: */ res.json({result1, result2}); }) .catch(error => { /* Handle/report error here, for instance:*/ res.status(500).send(/*...*/); }); });` In that, I hven't handled the [`fetch` footgun](http://blog.niftysnippets.org/2018/06/common-fetch-errors.html), you'll want to do that too. – T.J. Crowder Oct 13 '20 at 14:28

0 Answers0