0

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?

CodeMilian
  • 1,262
  • 2
  • 17
  • 41
  • While loop is like too fast, by the time it reaches there, it would go through a million loops, So basically you are blocking the entire process by a while loop, which is very very wrong. – Ashok Kumar Sahoo Feb 09 '16 at 07:15
  • That's what I figured. before using deasync I had a crazy loop that basically blocked everything. The framework is supposed to overcome that – CodeMilian Feb 09 '16 at 07:17
  • I changed my code to this just now and it appears to be working require('deasync').loopWhile(function(){return !ready;}); – CodeMilian Feb 09 '16 at 07:17
  • going to test a few more times before making it the answer – CodeMilian Feb 09 '16 at 07:17

2 Answers2

0

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;
}
CodeMilian
  • 1,262
  • 2
  • 17
  • 41
0

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

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

This will work properly.

Pradeep
  • 9,667
  • 13
  • 27
  • 34
Goutam Ghosh
  • 87
  • 1
  • 7