This content originally appeared on DEV Community and was authored by Adam Hawley
Intro
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 this StackBlitz
Conclusion
Hopefully you found this helpful, to get updates as soon as I release helpful guides such as this follow me on Twitter or Dev!
This content originally appeared on DEV Community and was authored by Adam Hawley
Adam Hawley | Sciencx (2022-04-12T19:48:48+00:00) Get Started with JavaScript Promises (in Under 2 Minutes). Retrieved from https://www.scien.cx/2022/04/12/get-started-with-javascript-promises-in-under-2-minutes/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.