Last Updated: February 25, 2016
·
1.366K
· maikel22

Make Node async operations sync

Sometimes methods on a node package do async operations and have no sync variants. Using 'deasync' we can make this a breeze and keeping your code clean.

Usage:

(replace yourAsyncMethod with your function)

console.log('starting');

sync.do(function(){
    yourAsyncMethod(function(){
        console.log('operation done');
        sync.done();
    });
});

console.log('end');

Definition:

var sync = {
    _deasync: require('deasync'),
    _done: false,
    do: function(callback, sleep) {
        this._done = false;
        callback();
        while ( ! this._done) {
            this._deasync.sleep(sleep ? sleep : 100);
        }
    },
    done: function() {
        this._done = true;
    }
}