Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Last active April 10, 2016 07:38
Show Gist options
  • Save softwarespot/8e8a33b6e34a69718541 to your computer and use it in GitHub Desktop.
Save softwarespot/8e8a33b6e34a69718541 to your computer and use it in GitHub Desktop.
Promises example using Promise and jQuery.Deferred
(function promiseExample(window, $, output, Math, Promise, setTimeout) {
var TIMEOUT = 2000;
var promise = null;
// Native
// Only call the Promise example if promises are supported in the browser natively
if (Promise !== undefined) {
// Create a new native promise object
promise = new Promise(function promise(resolve, reject) {
example(resolve, reject, 'native');
});
// On success
promise.then(function thenPromise(data) {
output.log(data);
});
// On failure
promise.catch(function catchPromise(data) {
output.log(data);
});
}
// jQuery
// Only call the jQuery example if jQuery exists
if ($ !== undefined) {
// Create a jQuery deferred object
var defer = $.Deferred(function deferred(defer) {
example(defer.resolve, defer.reject, 'jQuery');
});
// Get the promise interface so as not to expose resolve and reject
promise = defer.promise();
// On success
promise.then(function thenPromise(data) {
output.log(data);
});
// On failure
promise.fail(function failPromise(data) {
output.log(data);
});
}
/**
* Resolve or reject a promise.
*
* @param {function} resolve Resolve function
* @param {function} reject Reject function
* @return {undefined}
*/
function example(resolve, reject, type) {
setTimeout(function setTimeout() {
// Returns either zero or one
if (getInt(0, 1000)) {
resolve('The promise was resolved i.e. completed [' + type + ']');
} else {
reject('The promise was rejected i.e. failed [' + type + ']');
}
}, TIMEOUT);
}
/**
* Generate a random number
*
* @param {number} min Minimum value
* @param {number} max Maximum value
* @return {number} Returns a random number between the minimum and maximum values
*/
function getInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
}(window, window.jQuery, window.console, window.Math, window.Promise, window.setTimeout));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment