Monday, 15 May 2017

Can't set headers after they are sent after building array in loop

I'm attempting to build an array of objects and send to client. Receiving error:

    throw new Error('Can\'t set headers after they are sent.');
    ^

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)
    at ServerResponse.header (D:\Dropbox (Personal)\coding\coinTracker5\node_modules\expr                         ess\lib\response.js:725:10)
    at ServerResponse.send (D:\Dropbox (Personal)\coding\coinTracker5\node_modules\expres                         s\lib\response.js:170:12)
    at ServerResponse.json (D:\Dropbox (Personal)\coding\coinTracker5\node_modules\expres                         s\lib\response.js:256:15)
    at D:\Dropbox (Personal)\coding\coinTracker5\routes\index.js:58:11
    at D:\Dropbox (Personal)\coding\coinTracker5\node_modules\cryptox\lib\index.js:51:9
    at D:\Dropbox (Personal)\coding\coinTracker5\node_modules\cryptox\lib\bitfinex.js:93:                         13
    at D:\Dropbox (Personal)\coding\coinTracker5\node_modules\cryptox\lib\bitfinex.js:72:                         13
    at Request._callback (D:\Dropbox (Personal)\coding\coinTracker5\node_modules\bitfinex                         -api-node\rest.js:95:16)
    at Request.self.callback (D:\Dropbox (Personal)\coding\coinTracker5\node_modules\requ                         est\request.js:187:22)

I think res.json(rates) is only firing once, so I'm not sure why the headers are being set twice?

Also if there is a better way to build this array and send it to client, please enlighten me! Thank you

var rates = [];
for (var i = 0, len = cryptoxArray.length; i < len; i++) {

  cryptoxArray[i].getRate({
    pair: "XBT_USD"
  }, function(err, rateResponse) {
    if (!err)
      rates.push(rateResponse);

    if (i == len) {
      console.log('rates: ' + rates);
      res.json(rates);
    }
  });


via chuckieDub

No comments:

Post a Comment