vendredi 27 mars 2015

Have express.js wait until callback executes to send response

I have a pretty simple scenario, with a RESTful endpoint in Node / Express.js that needs to invoke another REST service and return its result.


The trouble I'm facing is the response in the Express method is being sent before the async callback returns.



var express = require('express');
var app = express();

app.post('/test', function(req, res) {
async.series([ function(callback) {
var httpConfig = app.config.evaluateRuleService;
logger.info("About to make request");
// make an async call here
require('../utils/http-wrapper/http').post(req.body, httpConfig,
function(err, data) {
logger.info("still have res: " + res);
logger.info("Got response: " + data);
callback(false, err);
});
} ],
function(err, results) {
logger.info("Inside collate method");
// correctly gets invoked after async call completes
// but res.json isn't sending anything to the client
res.json({
authorized : results.isAuthorized
});
})
// Problem: The response is being sent before the async call completes
});


Here's the log output:



"Listening on port 8897","time":"2015-03-27T19:22:24.435Z","v":0}
"About to make request","time":"2015-03-27T19:22:30.608Z","v":0}
fetch() POST http://localhost:8897/test
**<logs of the server method being invoked are printed out>**
"still have res: [object Object]","time":"2015-03-27T19:22:30.616Z","v":0}
"Got response: {\"isAuthorized\":true}","time":"2015-03-27T19:22:30.616Z","v":0}
"Inside collate method","time":"2015-03-27T19:22:30.617Z","v":0}


So the order occurs in an agreeable way, however, the clients invoking this endpoint are seeing an empty result being returned immediately, and not the expected authorized : results.isAuthorized which I'm trying to send to the response in the last callback.


Is there any way to keep a response open in Express until I'm ready to return the data?


Much thanks


Aucun commentaire:

Enregistrer un commentaire