A promise in JavaScript is much like a promise in real life. It's quite a fitting name and I applaud the person who thought of it. In code, you use it to do something, typically asynchronously. When the promise is complete, either one of two things happen: you fulfill the promise or you fail to fulfill the promise.
A Promise
is a constructor function, so you must use new
to create one. Here's what it looks like:
const pinkyPromise = new Promise((resolve, reject) => {
// your code here
});
You'll notice a Promise
takes in a function as an argument with two parameters: resolve
and reject
. Obviously, you can name these parameters whatever you want. I typically use res
and rej
because it's easier to type.
A promise has three states: pending
, fulfilled
and rejected
. The promise I showed you above will always be in the pending
state because we didn't tell the function how to fulfill the promise.
Here's how we can fulfill a promise:
const pinkyPromise = new Promise((res, rej) => {
if() {
resolve("Promise was fulfilled");
} else {
reject("Promise was rejected");
}
});
We added a simple if
statement that tells the promise what it should do if it's resolved or rejected. We use strings here but you can pass anything as the argument.
A typical use case scenario for promises is to fetch data from an external API or any sort of asynchronous function that takes an unknown amount of time to complete. Let's say we want to get weather data from an API. What do we do after it has successfully fulfilled its promise? That is where the then
method comes in:
const pinkyPromise = new Promise((res, rej) => {
if() {
resolve("Promise was fulfilled");
} else {
reject("Promise was rejected");
}
})
.then(result => {
console.log(result)
});
In the above example, we are telling the promise pinkyPromise
to log the results to our terminal so we can read it, like weather data. The then
method will only run when the promise has been resolved. The catch
method is used in very much the same way as then
except it only runs if it was rejected:
const pinkyPromise = new Promise((res, rej) => {
if() {
resolve("Promise was fulfilled");
} else {
reject("Promise was rejected");
}
})
.then(result => {
console.log(result)
})
.catch(error => {
console.log(error)
})
You can see that, again, we are just logging what we receive back into the console but this time it's the error
. Keep in mind result
and error
can be named whatever you want it to be and the then
and catch
methods can be on the same line as the closing parenthesis. I only put it on a new line to better see what we added to our promise.
And that's it! To recap, a JavaScript promise is usually used for an asynchronous task that takes an unknown amount of time to complete, like fetching for data. The promise is either resolved or rejected. If it's resolved, then the then
method will run. If it's rejected, then the catch
method will run.
Top comments (0)