我有以下功能:
function search(response) {
console.log("1");
step1().then(step2(response)).done();
console.log("4");
}
var step1=function()
{
var deferred = Q.defer();
searchOperations.performSearch(deferred);
return deferred.promise;
}
var step2 = function(response) {
var deferred = Q.defer();
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("someresult" + "\n");
response.end();
console.log("2");
deferred.resolve();
return deferred.promise;
}
那一个:
function performSearch(deferred) {
console.log("Request handler 'search' was called.");
var qryObj = {
"query": {
"match_all": {}
}
};
elasticSearchClient.search(index, type, qryObj).
on('data', function (data) {
// console.log(data)
setTimeout(function() {
console.log("3");
deferred.resolve();
}, 5000);
// deferred.resolve();
})
.on('error', function (err) {
console.log(err);
})
.exec();
}
预期输出为:1,4,3,2
但是我得到了这个输出: 1 2 4 3
为什么在步骤3之前调用第2步?
我的目的是只有在我从搜索回调中获取结果后才打印(第2步)结果(步骤3)。
答案 0 :(得分:0)
function search(response) {
console.log("1");
step1().then(step2(response)).done();
console.log("4");
}
应该是
function search(response) {
console.log("1");
step1().then(function () {
step2(response);
}).done();
console.log("4");
}
这相当于这样:
function search(response) {
console.log("1");
function callStep2() {
step2(response);
}
step1().then(callStep2).done();
console.log("4");
}