Jordan Jordan - 13 days ago 6
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 = "https://www.google.com"
var url2 = "https://www.yahoo.com"
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

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) {
console.log(url);
data = new Object();
console.log(data);
deferred = new q.defer();
console.log(deferred);
request({
url: url,
json: true
}, function (error, response, obj) {
if (!error && response.statusCode === 200) {
data = obj;
deferred.resolve();
console.log(deferred);
} else {
console.log('err');
}
});
return deferred.promise;
}


The problem is after the first
.then
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

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});
Comments