javascript - 如何从 mongodb 查询回调函数返回数据?
问题描述
当我登录points
查询回调函数时,它返回真值,但是当我在查询回调函数之外记录它时,它返回空对象 {}。如何访问 points
外部查询回调函数??
crypto.find({ "date": moment().format("YYYY-MM-DD hh:") + '00' }, function (err, result ) {
if (result.length > 0) {
result.forEach(signal => {
++x
points[x] = {};
for (let i = 0; i < 4; i++) {
if (i == 1) {
let currentPrice = self.getCurrentPrice(moment(signal.date).add(i, 'hours').format("YYYY-MM-DD hh:mm"));
points[x][i] = { currentPrice: currentPrice }
} else if (i == 2) {
let currentPrice = self.getCurrentPrice(moment(signal.date).add(i, 'hours').format("YYYY-MM-DD hh:mm"));
points[x][i] = { currentPrice: currentPrice }
} else if (i == 3) {
let currentPrice = self.getCurrentPrice(moment(signal.date).add(i, 'hours').format("YYYY-MM-DD hh:mm"));
points[x][i] = { currentPrice: currentPrice }
}
}
});
}
console.log(points); // loged true value
return points;
}).sort({ createdAt: -1 })
console.log(points); // loged {} empety object
解决方案
我认为回调外部的 console.log(points) 可能在回调内部的 console.log(points) 之前调用。也许你可以尝试这样的事情:
async function getPoints(){
try {
var result = await findMongoPromise();
console.log(result);
}
catch(error){
console.log('ERROR:', error)
}
}
function findMongoPromise(){
return new Promise((resolve,reject)=>{
crypto.find({ "date": moment().format("YYYY-MM-DD hh:") + '00' }, function (err, result ) {
if (result.length > 0) {
result.forEach(signal => {
++x
points[x] = {};
for (let i = 0; i < 4; i++) {
if (i == 1) {
let currentPrice = self.getCurrentPrice(moment(signal.date).add(i, 'hours').format("YYYY-MM-DD hh:mm"));
points[x][i] = { currentPrice: currentPrice }
} else if (i == 2) {
let currentPrice = self.getCurrentPrice(moment(signal.date).add(i, 'hours').format("YYYY-MM-DD hh:mm"));
points[x][i] = { currentPrice: currentPrice }
} else if (i == 3) {
let currentPrice = self.getCurrentPrice(moment(signal.date).add(i, 'hours').format("YYYY-MM-DD hh:mm"));
points[x][i] = { currentPrice: currentPrice }
}
}
});
resolve(points);
}
else {
reject('ERROR');
}
});
});
}
getPoints();
推荐阅读
- php - 使用 PHP 在 Mysql 中导入 CSV 文件,但仅导入 236 行中的 214 行
- azure - 如何通过 Powershell 获取新创建的 Azure VM 的 IP 地址
- reactjs - 如何将带参数的函数传递给反应中的子元素并立即调用它?
- kubernetes - Kubernetes 集群在扩展时不会自动缩减到默认节点数
- c# - Search string in excel file and return searched cell's rowindex and columnindex using OpenXML in C#
- liquibase - 使用 Docker 进行部署时如何在 Liquibase 中回滚
- android - 与底部对齐时 Adview 消失
- php - 如何使用 laravel eloquent paginate() 从数据库中的相关表中获取数据?
- arrays - 如何将字典值添加到 VBA 中的数组而不是引用
- apache-spark - KafkaUtils.createStream 会在一段时间后停止捕获数据