Jordan Jordan - 1 year ago 75
Node.js Question

Chain Promises Node.js using Q Not Working

Pretty simple Node.js (console app) code:

var request = require("request");
var q = require("q");
var data = new Object();
var deferred = new q.defer();

var url1 = ""
var url2 = ""

console.log('begin data1');
requestData(url1) //Promises seem to be working fine here
.then(function () { console.log('finished data1'); }) //At this point, we go back to async, and everything from here down executes at the same time.
.then(function () { console.log('begin data2'); })
.then(function () { requestData(url2); }) //Expected behavior is that it should pause here, and execute everything below after the request is complete.
.then(function () { console.log('finished data2'); })
.then(function () { console.log(data); })
.then(function () { console.log('finished write2'); })
.then(function () { console.log('operation completed!'); });

function requestData(url) {
data = new Object();
deferred = new q.defer();
url: url,
json: true
}, function (error, response, obj) {
if (!error && response.statusCode === 200) {
data = obj;
} else {
return deferred.promise;

The problem is after the first
statement, everything executes asynchronously. I want the second time I run 'requestData' call to be synchronous like the first.

Pardon my console logs for debugging purposes.

What am I doing wrong here?

Answer Source

The problem is you are not returning a promise in the then methods.

Try this:

...something.then(function() {  
        return requestData(url2);
}).then(function() { //called after requestData ended});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download