Friday 17 March 2017

Error handling with es6 async/await function, Unhandled promise rejection

I'm cleaning up some nested mongoose queries by using async/await functions. In this case I'm also using native JS promise library with mongoose.

With the following code, I still get this error in the console:

(node:3020) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Err: cCountFull(): true
(node:3020) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Code

let cCustomers = () => {
  return Customer.find(dfilter).skip(parseInt(data.start))
    .limit(altNum).sort(sOrder).lean()
    .exec(function (err, customers) {
      return err || customers
    });
};

let cCountFull = () => {
  Customer.count({}, function(err, countFull){
    err = true; //simulate error
    if (err) {
      // cb(true, err);
      Promise.reject('Err: cCountFull(): ' + err); return;
    };  
    Promise.resolve(countFull);      
  });
};

let cCountFiltered = () => {
  return Customer.find(dfilter).count({}, function(err, countFiltered){
    return err || countFiltered;
  });
};

(async function() {
  try {
    let countFull = await cCountFull();
    let countFiltered = await cCountFiltered();
    let customers = await cCustomers();
    let doc = {};
    doc.draw = parseInt(data.draw);
    doc.recordsTotal = parseInt(countFull); // total number of records in the database collection.
    doc.recordsFiltered = parseInt(countFiltered); //total records for this query 
    doc.data = customers;
    cb(false, doc);
  } catch(err) {
    console.log('err', err);
  };
})().catch(function (err) {console.log('err', err)})

I need cCountFull() cCountFiltered() and cCustomers() to complete before executing cb(false, doc). I put them in a try/catch block and then set err to true in one of the queries so it would return Promise.reject() and I could see how my error was being handled. But I'm still getting the message above in the console suggesting I'm not handling these errors correctly. Can anyone show me what i'm doing wrong and how to correct it?



via jtlindsey

No comments:

Post a Comment