简体   繁体   English

Node.js没有正确返回承诺

[英]Nodejs not returning promise properly

I'm working on a NodeJS + Express + Mongoose + MongoDB project. 我正在开发NodeJS + Express + Mongoose + MongoDB项目。

This code works fine: 这段代码可以正常工作:

var findRecord = function(id) {
  // find record by id
  return User.findOne({
    _id: id
  }).then(function(record) {
      // if record not found
      if (!record) {
        return Promise.reject(constant.NOT_FOUND);
      } else {
        // return found object
        return Promise.resolve({
            data: record,
            status: constant.READ_SUCCESS
        });
      }
    }, function() {
        // if there is error reading record
        return Promise.reject(constant.READ_ERROR);
    });
};

Don't know what is wrong with this one: 不知道这是怎么回事:

var allRecords = function(skip, limit) {
  // find all records
  return User.find({}).limit(limit).skip(skip)
    .then(function(records) {
        console.log('executed');
        // if records found
        return Promise.resolve({
            data: records,
            status: constant.READ_SUCCESS,
        });
    }, function() {
        return Promise.reject(constant.READ_ERROR);
    });
};

executed never prints on console 执行从不在控制台上打印

Even this one also don't work: 即使是这个也不起作用:

var allRecords = function(skip, limit) {
  // find all records
  return User.find({}).limit(limit).skip(skip)
    .exec(function(records) {
        console.log('executed');
        // if records found
        return Promise.resolve({
            data: records,
            status: constant.READ_SUCCESS,
        });
    }, function() {
        return Promise.reject(constant.READ_ERROR);
    });
};

You need to run exec method: 您需要运行exec方法:

User.find({}).limit(limit).skip(skip).exec();

Besides of this you shouldn't use Promise.resolve to return result from a promise, just return an object. 除此之外,您不应该使用Promise.resolve从promise返回结果,而只是返回一个对象。 Also, it's better to use catch callback, instead of second callback of then : 另外,最好使用catch回调,而不是then的第二个回调:

var allRecords = function(skip, limit) {
  return User.find({})
    .limit(limit)
    .skip(skip)
    .exec()
    .then(records => {
        console.log('executed');
        // if records found
        return {
            data: records,
            status: constant.READ_SUCCESS,
        };
    })
    .catch(err => Promise.reject(constant.READ_ERROR));
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM