JavaScript Promises - reject vs. throw -


i have read several articles on subject, still not clear me if there difference between promise.reject vs. throwing error. example,

using promise.reject

return asyncispermitted()     .then(function(result) {         if (result === true) {             return true;         }         else {             return promise.reject(new permissiondenied());         }     }); 

using throw

return asyncispermitted()     .then(function(result) {         if (result === true) {             return true;         }         else {             throw new permissiondenied();         }     }); 

my preference use throw because shorter, wondering if there advantage of 1 on other.

there no advantage of using 1 vs other, but, there specific case throw won't work. however, cases can fixed.

any time inside of promise callback, can use throw. however, if you're in other asynchronous callback, must use reject.

for example,

new promise(function() {    settimeout(function() {      throw 'or nah';      // return promise.reject('or nah'); won't work    }, 1000);  }).catch(function(e) {    console.log(e); // doesn't happen  });

won't trigger catch, instead you're left unresolved promise , uncaught exception. case want instead use reject. however, fix promisifying timeout:

function timeout(duration) { // joews    return new promise(function(resolve) {      settimeout(resolve, duration);    });  }    timeout(1000).then(function() {    throw 'worky!';    // return promise.reject('worky'); works  }).catch(function(e) {    console.log(e); // 'worky!'  });


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -