You are on page 1of 6

To make Medium work, we log user data.

By using Medium, you agree to our Privacy Policy, including


cookie policy.

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

How Promises Actually Work in JavaScript


Learn when and how to use them

Dev by RayRay
Mar 11 · 4 min read

Photo by Ferenc Almasi on Unsplash.

In the current age of JavaScript, Promises are the default way to handle asynchronous
behavior in JavaScript. But how do they work? Why should you understand them very
well?

In this article, I will dive into JavaScript Promises to understand what they do and
when you should use them.
To make Medium work, we log user data. By using Medium, you agree to our Privacy Policy, including
cookie policy.

A Promise in Real Life


When I make you a promise, you take my word that I will fulfill that promise.

But I don’t tell you when that promise will be fulfilled, so life goes on…

There are two possible scenarios: fulfillment or rejection.

Fulfillment
One day, I fulfill that promise. It makes you so happy that you post about it on Twitter!

Rejection
One day, I tell you that I can’t fulfill the promise.

You make a sad post on Twitter about how I didn’t do what I had promised.

Both scenarios cause an action. The first is a positive one, and the next is a negative
one.

Keep this scenario in mind while going through how JavaScript Promises work.

When To Use a Promise


JavaScript is synchronous. It runs from top to bottom. Every line of code below will
wait for the execution of the code above it.

But when you want to get data from an API, you don’t know how fast you will get the
data back. Rather, you don’t know if you will get the data or an error yet. Errors
happen all the time, and those things can’t be planned. But we can be prepared for it.

So when you’re waiting to get a result from the API, your code is blocking the browser.
It will freeze the browser. Neither we nor our users are happy about that at all!

Perfect situation for a Promise !


How
To make To Usework,
Medium a Promise
we log user data. By using Medium, you agree to our Privacy Policy, including
cookie policy.
Now that we know that you should use a Promise when you make Ajax requests, we
can dive into using Promises . First, I will show you how to define a function that

returns a Promise . Then, we will dive into how you can use a function that returns a

Promise .

Define a function with a Promise


Below is an example of a function that returns a Promise :

1 function doSomething(value) {
2 return new Promise((resolve, reject) => {
3 // Fake a API call
4 setTimeout(() => {
5 if(value) {
6 resolve(value)
7 } else {
8 reject('The Value Was Not Truthy')
9 }
10 }, 5000)
11 });
12 }

dosomething.js
hosted with ❤ by GitHub view raw

The function returns a Promise . This Promise can be resolved or rejected.

Like a real-life promise, a Promise can be fulfilled or rejected.

States
According to MDN Web Docs, a JavaScript Promise can have one of three states:

“- pending: initial state, neither fulfilled nor rejected.

- fulfilled: meaning that the operation was completed successfully.

- rejected: meaning that the operation failed.”

Pending
The pending state is the initial state. This means that we have this state as soon we call
the doSomething() function, so we don't know yet if the Promise is rejected or resolved.

Resolved
Inmake
To the example, if the
Medium work, value
we log is truthy,
user data. the
By using Promise
Medium, will be
you agree resolved.
to our In thisincluding
Privacy Policy, case, we
cookie policy.
pass the variable value in it to use it when we would call this function.

We can define our conditions to decide when to resolve our Promise .

Rejected
In the example, if the value is falsy, the Promise will be rejected. In this case, we pass
an error message. It's just a string here, but when you make an Ajax request, you pass
the server's error.

Use a Function With a Promise


Now that we know how to define a Promise , we can dive into how to use a function

that returns a Promise :

You can recognize a function that returns a Promise by the .then() method or an
await keyword. The catch will be called if there is an error in your Promise . So

making error handling for a Promise is pretty straightforward.

Promises are used in a lot of JavaScript libraries and frameworks as well. But the
simplest web API is the Fetch API, which you should use for making Ajax requests.
Check the tutorial below if you want to see how that works:

From XHR to Fetch With Async/Await on the Finish


Line
A look at the evolution and history of requests in JavaScript
betterprogramming.pub

Conclusion
Hopefully,
To make Medium thiswork,
helpswe you to understand
log user data. By using how you agreework
Promises
Medium, to ourand what
Privacy youincluding
Policy, can do with
cookie policy.
them.

If you have any questions about Promises , please let me know.

Happy coding!

Get my weekly newsletter “Developer Underdogs” with the best


developer content created by aspiring developers.

Read more from me

CSS variable with Styled Components


Use them easily in Next.js/React.js
devbyrayray.medium.com

How to use CSS Media Queries with Styled Components


in React.js
Use Media Queries Smarter In Styled Components
devbyrayray.medium.com

Developer Dilemmas: New Technology VS Old


Technology
Medium Short Story
devbyrayray.medium.com
To make Medium work, we log user data. By using Medium, you agree to our Privacy Policy, including
How
cookie To Build A Custom Checkbox With JavaScript
policy.

Learn JavaScript The Easy Way


javascript.plainenglish.io

Thanks to Anupam Chugh. 

Sign up for programming bytes


By Better Programming

A weekly newsletter sent every Friday with the best articles we published that week. Code tutorials,
advice, career opportunities, and more! Take a look.

You'll need to sign in or create an account to receive this


Get this newsletter
newsletter.

Programming JavaScript Typescript React Web Development

About Help Legal

Get the Medium app

You might also like