非阻塞MongoDB + NodeJS [英] Non-Blocking MongoDB + NodeJS
问题描述
我正在尝试在NodeJS
环境中的MongoDB
集合中查找文档.有什么方法可以执行以下操作?
I am trying to find a document in a MongoDB
collection in a NodeJS
environment. Is there any way to do the following?
这不起作用:
var foo = function (id) {
// find document
var document = database.find(id);
// do whatever with the document
...
}
这种方式创建一个块:
var foo = function (id) {
// find document
var document = database.find(id);
while (!database.find.done) {
//wait
}
// do whatever with the document
...
}
我想做什么:
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
...
}
我知道我可以使用回调,但是在NodeJS/JavaScript中是否有一种更简单的方法,就是暂停"然后继续"?抱歉,我还是Web开发的新手.
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.
推荐答案
这是不可能的.如果您担心回调的可读性,则可以考虑使用可编译为JavaScript的语言.例如, LiveScript 具有所谓的回叫",它们使代码看起来暂停了,但编译为回调功能:
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:
例如:
result <- mongodb.find id
console.log result
编译为:
mongodb.find(id, function(result){
return console.log(result);
});
这篇关于非阻塞MongoDB + NodeJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!