Created
October 6, 2017 13:14
-
-
Save ahgood/f8d464ef0df054772c90b6da65d7e0cb to your computer and use it in GitHub Desktop.
JavaScript Promise Examples
This file contains hidden or 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
//1. | |
new Promise(function(resolve, reject) { | |
console.log('A'); | |
resolve(); | |
}).then(function() { | |
console.log('B'); | |
}); | |
console.log('C'); | |
//A, C, B | |
//2. | |
function ajax(options) { | |
return new Promise(function(resolve, reject) { | |
jQuery.ajax(options).done(resolve).fail(reject); | |
}); | |
} | |
console.log('A'); | |
ajax({ url: '/' }).then(function(result) { | |
console.log(result.length); | |
console.log('B'); | |
}); | |
console.log('C'); | |
//3. | |
console.log('A'); | |
new Promise(function(resolve, reject) { | |
jQuery.ajax({ url: '/' }).done(resolve).fail(reject); | |
}).then(function(result) { | |
console.log(result.length); | |
console.log('B'); | |
}); | |
console.log('C'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source:
https://www.stephanboyer.com/post/107/fun-with-promises-in-javascript
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise