无法阅读财产'然后'未定义,函数不是异步

时间:2018-05-25 09:04:40

标签: node.js mongodb asynchronous async-await

我不确定为什么会发生这种情况,我试过asycn / await,bluebrid,内置的承诺,什么都行不通,这是我的代码:

const Promise = require('bluebird');
const mongoose = require('bluebird').promisifyAll(require('mongoose'));
const bar = require('./config/models/bar');

router.get('/foo', function(req, res) {
  getCollection('foo').then(data => res.sendStatus(200).json(data))
});

function getCollection() {
  new Promise(function(resolve, reject) {
    bar.findAsync({}, function(err, result) {
      if (err) {
        console.log(err);
      }
      console.log(result) //This prints the correct result to log
      resolve(result)
    })
  });
}

每当我转到/foo时,我都会TypeError: Cannot read property 'then' of undefined

1 个答案:

答案 0 :(得分:0)

您需要从Promise返回getCollection

function getCollection() {
  return new Promise(function(resolve, reject) {
    bar.findAsync({}, function(err, result) {
      if (err) {
        console.log(err);
      }
      console.log(result) //This prints the correct result to log
      resolve(result)
    })
  });
}