Promise - deferred and asynchronous computation
A Promise is an object that contains the future value of an asynchronous operation. For example, if you request some data from a server, a promise promises us to receive this data that we can use in the future.
At first, the promise has the status pending
, then it has one of: fulfilled
("successfully completed") or rejected
(" completed with an error ").
Pending
- The promise is pending if the result is not ready. That is, it is waiting for something to complete (for example, the completion of an asynchronous operation).Fulfilled
- Promise resolved if result is available. That is, something completed its execution (for example, an asynchronous operation) and everything went well.Rejected
- Promise was rejected if an error occurred during execution.
Create a promise
A Promise
object is created using the new keyword and its own constructor.
The Promise constructor takes one argument, a callback, also known as an execution function⚙️, which takes 2 callbacks, resolve
and reject
.
The executive function is executed immediately after the promise is created. A promise is made fulfilled by calling resolve
and rejected by calling reject
.
const promise = new Promise((resolve, reject) => {
if (allWentWell) {
resolve('Everything went great!')
} else {
reject('Something went wrong')
}
})
resolve
and reject
take one argument, which can be a string, number, boolean expression, array, or object.
To provide a function with promises functionality, you just need to return a Promise
object in it:
function myAsyncFunction(url) {
return new Promise((resolve, reject) => {
// function code
})
}
Using a promise
Promises are used with the then()
and catch()
methods.
then
The then
method is used to run functions on a positive or negative promise.
The syntax for the then
method is:
promise.then(
function (result) {
/* handle successful execution */
},
function (error) {
/* will handle the error */
}
)
The first 1️⃣ argument of the then
method is a function⚙️ that is executed when the promise is passed to the" completed successfully "state and receives the result.
The second argument to then
is a function⚙️ that is executed when a promise enters the completed with error state and receives an error.
An example of the then
method:
let promise = new Promise(function (resolve, reject) {
setTimeout(() => resolve('done!'), 1000)
})
// resolve will run the first function passed to .then
promise.then(
result => alert(result), // displays "done!" in one second
error => alert(error) // will not be triggered
)
And in case of an error in a promise, the second will be executed:
let promise = new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error('Whoops!')), 1000)
})
// reject will run the second function passed to .then
promise.then(
result => alert(result), // will not be triggered
error => alert(error) // prints "Error: Whoops!" one second later
)
If you need to display only the result of a successful execution, then only one function can be passed to then
:
let promise = new Promise(resolve => {
setTimeout(() => resolve('done!'), 1000)
})
promise.then(alert) // will print "done!" one second later
catch
To catch errors, the catch
method is used. It can be used instead of the then
method to display error messages.
The syntax for the catch method is:
let promise = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('Error!')), 1000)
})
promise.catch(alert) // will print "Error: Error!" one second later
promise.all
This method takes an array of promises and returns a new promise that will be fulfilled when all the promises within the array are fulfilled or rejected as soon as a promise is encountered that is rejected.
For example:
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise1 completed')
}, 2000)
})
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise2 completed')
}, 1500)
})
Promise.all([promise1, promise2])
.then(data => console.log(data[0], data[1]))
.catch(error => console.log(error))
Here, the argument inside then()
is an array that contains the values of the promises in the same order in which they were passed to Promise.all()
.
Problems?
Write to Discord chat.
Questions:
What is the name of the method that is called when the promise is successful?
reject
resolve
What method can be used to check the fulfillment of all promises in the array?
promise.all
promise.race
What method is used to catch errors in promises?
then
catch
In order to understand how much you learned this lesson, take the test on the mobile application of our school on this topic.
Links:
Contributors ✨
Thanks goes to these wonderful people (emoji key):
Philipp Dvinyaninov | Dmitriy Vasilev 💵 | Resoner2005 🐛 🎨 🖋 | Navernoss 🖋 🐛 🎨 |