Non-Blocking MongoDB + NodeJS

2019-08-01 06:36发布

I am trying to find a document in a MongoDB collection in a NodeJS environment. Is there any way to do the following?

This is not working:

var foo = function (id) {
    // find document
    var document = database.find(id);
    // do whatever with the document
    ...
}

This way creates a block :

var foo = function (id) {
    // find document
    var document = database.find(id);
    while (!database.find.done) {
        //wait
    }
    // do whatever with the document
    ...
}

What I want to do :

var foo = function (id) {
    // find document
    var document = database.find(id);
    // pause out of execution flow 
    // continue after find is finished
    // do whatever with the document
    ...
}

I know I can use a callback but is there a simpler way of just "pausing" and then "continuing" in NodeJS/JavaScript? Sorry, I am still pretty new to web development.

1条回答
Emotional °昔
2楼-- · 2019-08-01 07:07

This is not possible. If you are concerned about the readability of callbacks you may consider using a language that compiles to JavaScript. LiveScript for example has so called “Backcalls”, they make the code appear to be pausing, but compile to a callback function:

For example:

result <- mongodb.find id
console.log result

compiles to:

mongodb.find(id, function(result){
  return console.log(result);
});
查看更多
登录 后发表回答