Promises - Error Handling
by wimpyprogrammer
HTML
<div id="result"></div>
CSS
#result {
font-size: x-large;
padding: 1em;
}
JavaScript
var result = document.getElementById('result');
function write(text) {
result.innerHTML += text + '<br/>';
}
function getProductNative(productId) {
return Promise.reject(new Error('Something went wrong!'))
// Swallow any errors (not a good practice!)
['catch'](function() { return 'Nah its cool'; });
}
function getProductjQuery(productId) {
if (!productId) {
return Promise.resolve(null);
}
var url = 'bad url';
var mock = { name: 'Widget', price: productId };
var data = { json: JSON.stringify(mock) };
return jQuery.post(url, data)
.then(null, function(res) {
// Swallow any errors (not a good practice!)
return null;
});
}
getProductjQuery(5)
.then(function(res) { write('then ' + JSON.stringify(res)); })
.then(null, function (res) { write('catch ' + JSON.stringify(res)); });
getProductNative(5)
.then(function(res) { write('then ' + JSON.stringify(res)); })
.then(null, function (res) { write('catch ' + JSON.stringify(res)); });