1

I'm trying to use 2 promises, the second promise depends on the first one. And a 3 promise depends on both promises. But when first promise fails I get this error in the second promise:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'name' of null

This is my code:

var Asset  = require('../models/index').Asset;
var Price = require('../models/index').Price;

var currency = req.params.currency;

var values = { 
                where: { slugify_url: currency },                    
            };

// get asset information 
var promisse_asset = Asset.findOne(values); 


// get prices information on this asset
var promisse_prices = promisse_asset.then(function(asset) {

    console.log(asset); // outputs null
    // some processing
    if (!!asset) {
        ...  


});


return Promise.all([promisse_asset, promisse_prices]).then(function([asset, results]) {
    ...

How can I fix this? How can I handle when I don't find an Asset in my database?

Filipe Ferminiano
  • 8,373
  • 25
  • 104
  • 174
  • 1
    You seem to simply be missing a `catch` (or second `then` argument). Without it, you get that _"unhandled promise rejection"_ error – Phil Dec 27 '17 at 03:16
  • @Phil I put a catch after the first promise, but it seems it is not entering in the catch condition. How should I do it? – Filipe Ferminiano Dec 27 '17 at 03:20
  • 1
    Ah, so the first promise is resolving successfully, just with a `null` value. You should throw an error in that case to cause the promise to fail. That one would need to be caught in the `Promise.all` promise – Phil Dec 27 '17 at 03:24
  • @Phil thanks! I added the catch to the third promise and it worked. – Filipe Ferminiano Dec 27 '17 at 03:32

1 Answers1

1

There is a situation where you want to batch process promises and get all the results including rejected ones with Promise.all. How you can do that is explained here (last code block).

There is a situation where you want to catch a rejecting promise on the queue and not on the stack without getting warnings (soon to be deprecated and getting errors). How you can do that is explained here.

Or you just wanted to reject a promise because the resolve value is not what you expected, you can throw as provided by Phil or return a Promise.reject("Something should not be null").

HMR
  • 37,593
  • 24
  • 91
  • 160