Non-Blocking MongoDB + NodeJS

≡放荡痞女 提交于 2019-12-13 00:28:19

问题


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:


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


来源:https://stackoverflow.com/questions/22160709/non-blocking-mongodb-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!