Smilyface Smilyface - 5 months ago 10
Javascript Question

Promises error in then function

How do we deal with errors that happen in the

function of a promise?

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

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

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
throwing an error? I thought the
function of the promise only deals with the
handler. Does it also deal with errors thrown in the


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"