【发布时间】:2018-07-25 08:50:47
【问题描述】:
总的来说,我是 nodejs 和 javascript 的初学者。我想访问一个集合,然后将我检索到的查询存储到一个数组中,以便稍后我可以使用该数组做更多的事情。 但是,当我将结果存储在数组中时,它不在函数之外。这是我的代码
const http = require('http');
const bodyParser = require('body-parser');
const locations = require('./models/vicitmsLocation');
const async = require('async');
var postcode = [];
locations.getAllTheIncidents({},function (err, results) {
if (err) {
throw err;
} else {
postcode.push(results);
//Here the code works and array will be populated with data I want
console.log(postcode);
}
});
//Here it doesnt work and array is empty.
console.log(postcode);
我知道这可能是 nodejs 和 mongo 的异步性质的问题,但我似乎无法弄清楚为什么会发生这种情况。
【问题讨论】:
-
我不太明白这对我有什么帮助!
-
由于异步特性,最后一个控制台在 getAllTheIncidents 回调返回数据之前执行。因此,如果您的下一个代码依赖于回调的结果,那么您必须在回调函数内部编写。