Ashutosh
Ashutosh

Reputation: 4675

Nodejs not returning promise properly

I'm working on a NodeJS + Express + Mongoose + MongoDB project.

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);
    });
};

Upvotes: 0

Views: 50

Answers (1)

alexmac
alexmac

Reputation: 19617

You need to run exec method:

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. Also, it's better to use catch callback, instead of second callback of 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));
};

Upvotes: 1

Related Questions