JavaScript promises lets us add non-IO-blocking, asynchronous code easily into our JavaScript app sequentially.
Therefore, they’re used everywhere.
In this article, we’ll look at how to use promises in our JavaScript code.
Create a Promise that Resolves
We can create a promise that resolves with Promise.resolve
.
For instance, we can write:
Promise.resolve(1)
.then((val) => console.log(val))
Then val
is 1 since we passed in 1 to Promise.resolve
.
Create a Promise that Rejects
We can create a promise that resolves with Promise.reject
.
For instance, we can write:
Promise.reject('error')
.catch((err) => console.log(err))
Then err is 'error'
since the catch
callback catches the reason value of the rejected promise.
Catching Rejected Promises
We can handle errors that are raised by rejected promises with the Promise.prototype.catch
instance method.
For instance, we can write:
Promise.reject('error')
.catch((err) => console.log(err))
Then err is 'error'
since the catch
callback catches the reason value of the rejected promise.
This lets us handle the value from the first rejected promises.
Get Value from Resolved Promises
We can use the Promise.prototype.then
method to get value from resolved promises.
For instance, we can write:
Promise.resolve(1)
.then(() => Promise.resolve(2))
.then((val) => console.log(val))
We call then
with a callback with a parameter to get the resolved value from the previously resolved promise.
So val
is 2.
Run Code Regardless of Promise Result
We can use the Promise.prototype.finally
method to run code regardless of what happens to the promises.
For instance, if we have:
Promise.reject('error')
.catch((err) => console.log(err))
.finally(() => console.log('finally'))
Then we see 'error'
and 'finally'
logged since the finally
callback runs regardless of whether a promise is resolved or rejected.
Conclusion
We can use promises to make writing async JavaScript code easy.