A promise is an asynchronous action with two main outcomes upon completion. In both cases, we notify any interested functions of the result’s value. A promise can either be successful (a resolve) or fail (a reject).
Why do we even have promises? These are cleaner than using callbacks. We also don’t need to always have a reject. We could have a promise that only resolves.
Promises are used primarily in JavaScript. We instantiate a new promise with:
let p = new Promise ((resolve, reject) => {
// some operation
let a = operation()
if (a.failed()) {
resolve()
} else {
reject()
}
})
We call the promise with:
p.then((output) => {
// code that executes for a successful promise
}).catch((output) => {
// code that executes for an unsuccessful promise
})
where code after the .then
method is executed.