What are Promises?
What are Promises? 관련
Promises are a very important concept in JavaScript, almost certain to be asked in interviews. Promises are used for asynchronous operations in JavaScript like timeouts or API calls.
Promises use a Promise object that exists in one of three states: pending, fulfilled (resolved), and rejected. When an asynchronous operation ends, a promise can either be resolved (successful) or rejected (failure).
Let's take a simple example:
function asyncOperation() {
return new Promise((resolve, reject) => {
const x = 1 + Math.random() * 10;
if (x < 5)
resolve("Successful");
else
reject("Error");
});
}
The above function returns a promise that performs an asynchronous operation.
- If the operation is successful, the
resolve
method is called to indicate that the promise has been fulfilled. - If the operation fails, the
reject
method is called to indicate that the promise has been rejected.
In this example, these methods are called at random. To handle this promise in your code, use the then
and catch
methods.
asyncOperation()
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
- The
then
method takes a callback function that executes if the promise was resolved. It takes a response object as an argument that is equal to the object you pass in theresolve
method. - The
catch
method takes a callback function that executes if the promise was rejected and takes an error object as argument that is passed in thereject
method.
The above code prints "Successful" and "Error" at random.
Apart from the basics, the Promise object also contains useful methods that work with multiple promises: Promise.all()
, Promise.any()
, Promise.race()
.
Read the following tutorial to learn about promises in detail