简体   繁体   中英

Using Q on nodejs not working as expected

I have the following functions:

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

and that one:

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

The expected output is: 1, 4 , 3, 2

However I get this output: 1 2 4 3

Why step 2 is invoked before step 3?

My intention is to print(step 2) the results only after I get them from the searching callback (step 3).

the problem is, that you are calling step2 instead of passing it.

function search(response) {
    console.log("1");
    step1().then(step2(response)).done();
    console.log("4");
}

should be

function search(response) {
    console.log("1");
    step1().then(function () {
        step2(response);
    }).done();
    console.log("4");
}

this is equivalent to something like this:

function search(response) {
    console.log("1");
    function callStep2() {
        step2(response);
    }
    step1().then(callStep2).done();
    console.log("4");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM