JavaScript Promises
1 min readMay 21, 2021
What are Promises?
- Similar to callback functions…however they are MUCH cleaner. If you were to use callback functions for every condition, you’d be in callback hell.
Use Cases:
- Tell code what to do when an action succeeds (resolve)
- Tell code what to do when an action fails (reject)
- Chaining | A promise chain will add a .then statement allowing for cleaner code
Syntax of creating a promise…
let wakeUp = new Promise((resolve, reject) => {let a = "awake"if (a == "awake"){
resolve('Good Morning!')
}else{
reject('It is time to wake up!')}
})
console.log(wakeUp)// this logs...Promise {<fulfilled>: "Good Morning!"}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "Good Morning!"
Traditional callback functions may look like this…
doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
console.log('Got the final result: ' + finalResult);
}, failureCallback);
}, failureCallback);
}, failureCallback);
But a promise chain can look like this…
doSomething()
.then(function(result) {
return doSomethingElse(result);
})
.then(function(newResult) {
return doThirdThing(newResult);
})
.then(function(finalResult) {
console.log('Got the final result: ' + finalResult);
})
.catch(failureCallback);
Learn more about promises on the MDN Webiste: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises