首页 > 解决方案 > 如何从 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

标签: javascriptnode.jscallback

解决方案


我认为回调外部的 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(); 


推荐阅读