2014-03-04 146 views
1

我正在尝试在NodeJS环境中的MongoDB集合中找到文档。有什么办法可以做到以下几点?非阻塞MongoDB + NodeJS

这不是工作:

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开发还很陌生。

回答

1

这是不可能的。如果您担心回调的可读性,可以考虑使用编译为JavaScript的语言。 LiveScript例如有所谓的“Backcalls”,他们使代码显示为暂停,但编译为一个回调函数:

例如:

result <- mongodb.find id 
console.log result 

编译为:

mongodb.find(id, function(result){ 
    return console.log(result); 
}); 
+0

这我想的。 :(感谢您告诉我有关LiveScript的信息! – user2702669