Introduction
Welcome to an extremely brief introduction to JavaScript Promises. After getting to grips with Promises myself I thought I would share the essentials that I needed to put them into practice.
Basics of JS Promises
Promises can be defined with the following recipe:
function function1 () {
return new Promise ((resolve, reject) => {
try {
doSomeStuff()
resolve()
} catch (err) {
reject(err)
}
})
}
resolve()
should be called if the operation associated with the Promise has been successful. reject()
should be called if the Promise could not be resolved, maybe there was some sort of problem when trying to perform the associated operation.
The caller function then has the option to asynchronously wait for the Promise to resolve using await
or the then()
method of Promises. To use await
, declare the entire function as asynchronous using the async
keyword. Here are examples of both:
async function callerFunc1() {
// Use 'await'
await function1()
}
function callerFunc2() {
// Use '.then()'
function1().then(() => {
doSomethingAfterwards()
})
}
Two extra things about Promise.then()
. Firstly, we can chain .then()
statements together to make something that operates like so:
function callerFunc3() {
function1.then(() => {
console.log('First thing finished')
}).then(() => {
console.log('Second thing finished')
})
}
Secondly, then()
can actually take two arguments: one in case the Promise resolves and another to handle the case when the Promise rejects.
function callerFunc4() {
function1.then(() => {
console.log('Everything went to plan!')
}, () => {
console.log('The Promise rejected :(')
})
}
If you want to see these examples in action, check out StackBlitz