Skip to content

Instantly share code, notes, and snippets.

@joe-oli
Forked from santisbon/promises.js
Created December 31, 2021 06:27
Show Gist options
  • Save joe-oli/7897f21cfc34d4c38d55d820c76a0bc7 to your computer and use it in GitHub Desktop.
Save joe-oli/7897f21cfc34d4c38d55d820c76a0bc7 to your computer and use it in GitHub Desktop.
Promises example based on Mozilla Developer Network documentation
/*jslint devel: true, browser: true, es5: true */
/*global Promise */
var promiseCount = 0;
function testPromise() {
'use strict';
promiseCount += 1;
var thisPromiseCount = promiseCount;
console.log(thisPromiseCount + ') Started (Sync code started)');
// We make a new promise: we promise the string 'result' (after waiting 3s)
var p1 = new Promise(
// The resolver function is called with the ability to resolve or reject the promise
function (resolve, reject) {
console.log(thisPromiseCount + ') Promise started (Async code started)');
// This is only an example to create asynchronism
window.setTimeout(
function () {
// We fulfill the promise !
resolve(thisPromiseCount);
},
Math.random() * 2000 + 1000
);
}
);
// We define what to do when the promise is resolved/fulfilled with the then() call,
// and the catch() method defines what to do if the promise is rejected.
p1
.then(function (val) {
// Log the fulfillment value
console.log(val + ') Promise fulfilled (Async code terminated)');
})
.catch(function (reason) {
// Log the rejection reason
console.log('Handle rejected promise (' + reason + ') here.');
});
console.log(thisPromiseCount + ') Promise made (Sync code terminated)');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment