Skip to content

Instantly share code, notes, and snippets.

@sam-ngu
Last active April 3, 2020 02:57
Show Gist options
  • Save sam-ngu/3811b4bada877ed3fbd9a57e01ba0266 to your computer and use it in GitHub Desktop.
Save sam-ngu/3811b4bada877ed3fbd9a57e01ba0266 to your computer and use it in GitHub Desktop.
Demonstration on how Promises work in Javascript
// creating a new promise by instantiating the Promise Class
let somePromise = new Promise(function(resolve, reject){
// the resolve and reject arguments are callback functions to be called.
// resolve: to be called when the promise is successful. We can pass data to it for the subsequent the 'then' method
// reject: to be called when the promise is unsuccessful. Again we can pass data to it for the 'catch' method
try{
// to mimick asynchoronous behaviour,
// trigger the timeout callback in 1 sec
setTimeout(function(){
console.log('hey there 1 sec later.')
// 'success promise data' is passed into the 'then' callback function
resolve('success promise data')
}, 1000)
}catch(error){
// in case of any errors, we will handle them here
// this is the best place to use the reject callback
reject('oops there is an error.')
}
});
somePromise.then(function(response){
// this function will only be triggered when the promise is successfully resolved.
// the 'response' argument would be whatever we passed into the resolve callback up there ^
// in this case it would be the String 'hey there 1 sec later.'
console.log(response); // expected output: 'hey there 1 sec later.'
}).catch(function(error){
// on the other hand, this function will only be triggered when the promise is not fulfilled. eg when there is an error
// if the promise failed, we would expect the 'error' argument to be: 'oops there is an error.'
console.log(error); // expected output: 'oops there is an error.' if the catch block runs.
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment