Mongoose synchronousFind

174 Views Asked by At

I am trying to build a synchronous mongoose find. I adopted the use of deasync. https://www.npmjs.com/package/deasync

This is currently working for saves but it is not working for queries

exports.synchronousFind = function (instanceModel, query) {
    var ready = false;
    var result = null;
    instanceModel.find(query, function (err, tenantUser) {
        ready = true;
        if (err) {
            console.log(err);
        } else {
            result = tenantUser;
        }
    });

    while (ready === false) {
        require('deasync').runLoopOnce();
    }
    return result;
}

This part of the code

while (ready === false) {
    require('deasync').runLoopOnce();
}

Just hangs forever and eventually it goes through. Does anyone have any ideas?

2

There are 2 best solutions below

0
CodeMilian On

I changed my code to this and it is now working properly as expected

exports.synchronousFind = function (instanceModel, query) {
    var ready = false;
    var result = null;
    instanceModel.find(query, function (err, tenantUser) {
        ready = true;
        if (err) {
            console.log(err);
        } else {
            result = tenantUser;
        }
    });

    require('deasync').loopWhile(function(){return !ready;});

    /*while (ready === false) {
        require('deasync').runLoopOnce();
    }*/
    return result;
}
0
Goutam Ghosh On

See the below code: Write the while loop in this way

while (!ready) {
    require('deasync').runLoopOnce();
}

This will work properly.