Promises - jQuery
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/><hr/>';
}
function getProduct(productId) {
if (!productId) {
// 1. Always return a Promise
return Promise.resolve(null);
}
var url = '/echo/json/';
var mock = { name: 'Widget', price: productId };
var data = { json: JSON.stringify(mock) };
return jQuery.post(url, data);
}
// 2. Beware of custom Promise methods!
getProduct(6)
.success(function(res) { write('success ' + JSON.stringify(res)); })
.error(function(res) { write('error ' + JSON.stringify(res)); });
// 3. No support for catch() in jQuery
getProduct(5)
.then(function(res) { write('then ' + JSON.stringify(res)); })
.then(null, function (res) { write('catch ' + JSON.stringify(res)); });