gpt4 book ai didi

javascript - 为什么 NodeJS shell 和编译器在变量赋值方面存在分歧?

转载 作者:行者123 更新时间:2023-12-03 09:38:43 24 4
gpt4 key购买 nike

以下是文件tags.js的内容。

//the following initializes the MongoDB library for Javascript.
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');

//connection URL
abc = 'mongodb://localhost:27017/abcbase/

/* the following is a global variable
where I want retrieved content */
var arrayToReturn = [];

/* toFind is a dictionary, toSearch is a
MongoDB collection (input is its name as a string) */
function findElemHelper(toSearch, toFind) {
/* establishes connection to the database abcbase
and runs the contents of the function that is
the second input */
MongoClient.connect(abc, function(err, db) {
/* coll is the collection being searched.
tempCurs is the results of the search returned
as a cursor
*/
coll = db.collection(toSearch);
tempCurs = coll.find(toFind);
/* the three lines below this comment
form the crux of my problem. I expect
arrayToReturn to be assigned to docs
(the contents of the cursor received by
the find function). Instead it seems like
it is declaring a new variable in local scope.*/
tempCurs.toArray(function(err, docs) {
arrayToReturn = docs;
});
});
}

function findElem(toSearch, toFind) {
findElemHelper(toSearch, toFind);
return arrayToReturn;
}

function returnF() {
return arrayToReturn;
}

var ln = findElem("userCollection", {});
var lm = returnF();

console.log(ln);
console.log(lm);

当我使用 Node 解释器和命令 node tag.js 运行该文件时,它会打印

[]
[]

当我在 Node 解释器上运行相同的代码时(我从终端使用命令 node 输入并将相同的代码复制粘贴到 shell 中),console.log( ln) 打印 []console.log(lm) 打印我想从 MongoDB 检索的文档内容。

有人可以解释一下这种行为吗?

最佳答案

正如一些评论者指出的那样,问题在于 findElemHelper 方法的异步性质。这个long, but detailed answer发布在其中一条评论中,解释了 JavaScript 中异步背后的基础知识以及如何处理这种编码风格。

简而言之,对于异步代码,您不能假设操作顺序与代码中的语句相同。您正确地确定了问题症结所在的位置,但问题不在于范围,而是每当数据库返回数据时都会调用您传递到 tempCurs.toArray 的函数,这可能是文件的其余部分执行完毕后。 (传递到 MongoClient.connect 的函数也是如此,您最终可能会在数据库连接之前调用 console.log!)

以下是我们如何通过回调解决问题,目标是构建我们的代码,以便我们确定数据库在调用 console.log 之前已返回数据:

var MongoClient = require('mongodb').MongoClient;

var abc = 'mongodb://localhost:27017/abcbase/';

/**
* Take a callback function as the last parameter which will
* be called when the array is retrieved.
*/
function findElem(toSearch, toFind, callback) {

MongoClient.connect(abc, function(err, db) {

var coll = db.collection(toSearch);
var tempCurs = coll.find(toFind);
tempCurs.toArray(callback);

});
}

findElem("userCollection", {}, function(err, docs) {

console.log(docs);

});

关于javascript - 为什么 NodeJS shell 和编译器在变量赋值方面存在分歧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31249377/

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