非常简单的Node.js(控制台应用)代码:
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;
}
问题出在第一个.then
语句之后,所有内容都是异步执行的。我希望第二次运行'requestData'调用与第一次调用同步。
请原谅我的控制台日志以进行调试。
我在这里做错了什么?
答案 0 :(得分:2)
问题是你没有在value
方法中返回一个承诺。
试试这个:
then