I am trying to build a simple node waterfall via async module. I'm just getting started with asynchronous programming in node.
Basically - how to call callback() inside http.request function to continue waterfall AFTER response IS END?
async.waterfall([
function (callback) {
var req = http.request(options, function (response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
/* I want to call callback() AFTER `response` is END */
});
});
req.end();
},
function (response, callback) {
// some operations WITH request `output`
}], function (err, results) {
// end
});
In JavaScript nested function see all parent variables. It is called closure.
That's why you can call your callback directly in the end event listener:
async.waterfall([
function (callback) {
var req = http.request(options, function (response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
/* I want to call callback() AFTER `response` is END */
callback(null, str);
});
});
req.end();
},
function (response, callback) {
// some operations WITH request `output`
}
], function (err, results) {
// end
});