Turn asynchronous functions to their synchronous counterpart

Recently, asynchronous programming becomes a hit as slow jobs can perform while not blocking other jobs to be done. However, sometimes we want something to be done in a synchronous way like getting a single value from a query (you know callbacks are clumsy). In order to solve the  problem, turning asynchronous functions to synchronous can solve the problem.

To turn asynchronous functions to synchronous, we need to set up a loop checking the result, therefore cause blocking.

Here’s the code: (we use javascript here because it’s straightforward)

function somethingSync(args){
    var ret; //the result-holding variable
    //doing something async here...
    somethingAsync(args,function(result){
        ret = result;
    });
    while(ret === undefined){} //wait for the result until it's available, cause the blocking
    return ret;
}

4 Replies to “Turn asynchronous functions to their synchronous counterpart”

Leave a Reply

Your email address will not be published. Required fields are marked *