gpt4 book ai didi

node.js - 非阻塞 MongoDB + NodeJS

转载 作者:太空宇宙 更新时间:2023-11-04 01:06:55 24 4
gpt4 key购买 nike

我正在尝试在 NodeJS 环境中的 MongoDB 集合中查找文档。有没有办法做到以下几点?

这不起作用:

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

这种方式创建一个 block :

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 中“暂停”然后“继续”?抱歉,我对网络开发还很陌生。

最佳答案

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

例如:

result <- mongodb.find id
console.log result

编译为:

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

关于node.js - 非阻塞 MongoDB + NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22160709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com