Smilyface Smilyface - 4 months ago 9
Javascript Question

Promises error in then function

How do we deal with errors that happen in the

then
function of a promise?

getLocationId(lat, lon, callback)
{
let self = this;

return this._geocoder.reverse({lat: lat, lon: lon})
.then(this._parse)
.catch(function(err) {
callback(err);
});
}

_parse(res)
{
if (res.length < 1)
throw new Error('No results from Maps API');

let value = res[0].administrativeLevels;

if (!value || value.length < 1) {
throw new Error('No administrative levels available');
}

if ('level2long' in value)
return value.level2long;
if ('level1long' in value)
return value.level1long;

throw new Error('No suitable location found');
}


For instance, how do I deal with
this._parse
throwing an error? I thought the
catch
function of the promise only deals with the
reject
handler. Does it also deal with errors thrown in the
then
?

Answer

An exception thrown in any .then() handler will automatically be caught by the promise infrastructure and will turn the current promise chain into a rejected promise. The chain will then jump to the next .catch() handler where the exception will be the error reject reason.

Here's an example:

Promise.resolve().then(function() {
    throw "foo";
}).then(function() {
     console.log("in 2nd .then() handler");     // will not get here
}).catch(function(err) {
    console.log(err);                           // will show "foo"
});