简体   繁体   中英

How to make synchronous calls in Nodejs based on conditions

I am trying to create an array set from the output of API calls. All API calls are based on condition. I've tried below code.

var a = true;
var b = false;
var c = true;


var result = [];

if(a)
{
    callApi("a", function(data){

        result.push(data); //data = this is a

    })
}

if(b)
{
    callApi("b", function(data){

        result.push(data); //data = this is b

    })
}

if(c)
{
    callApi("c", function(data){

        result.push(data); //data = this is c

    })
}


console.log(result);

Output should be

["this is a", "this is c"];

"b" should not come here since condition is false for it.

But it shows blank array because it is not waiting for callback.

[]

How can I make the whole process synchronous?

How can I make the whole process synchronous?

You absolutely can't and should forget about it. You've got a list of asynchronous functions and you should consume the results of those asynchronous functions once all of them has finished executing. It's the way async functions work.

So one possibility is to promisify your callapi function using the q module:

function promisify(arg) {
    var deferred = Q.defer();
    callApi(arg, function(data) {
        deferred.resolve(data);
    });
    return deferred;
}

Now that you've done that, things are getting much easier:

var a = true;
var b = false;
var c = true;
var promises = [];

if (a) {
    promises.push(promisify('a'));
}

if (b) {
    promises.push(promisify('b'));
}

if (c) {
    promises.push(promisify('c'));
}

and now that you've got the promises array it's as simple as waiting for all of them to get settled and simply consume the results:

Q.allSettled(promises).then(function(results) {
    // TODO: do something with the results here
    console.log(results);
});

https://github.com/caolan/async

async.series([
    function(callback){
        // do some stuff ...
        callback(null, 'one');
    },
    function(callback){
        // do some more stuff ...
        callback(null, 'two');
    }
],
// optional callback
function(err, results){
    // results is now equal to ['one', 'two']
});

also u can choose to do processing in parallel or series

in each function u can put ur if logic , if true do callback(null,res) and it get pushed to result array , if false do callback(null,null)

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