CodeMilian
CodeMilian

Reputation: 1290

Mongoose synchronousFind

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?

Upvotes: 0

Views: 173

Answers (2)

Goutam Ghosh
Goutam Ghosh

Reputation: 87

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

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

This will work properly.

Upvotes: 0

CodeMilian
CodeMilian

Reputation: 1290

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

Upvotes: 0

Related Questions