Last active
March 16, 2023 15:59
-
-
Save santisbon/7953f7c2784ff629211f to your computer and use it in GitHub Desktop.
#javascript #promise example based on Mozilla Developer Network documentation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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