Promise in JavaScript

Jake jonggu baek
2 min readJan 13, 2024

--

When working with basic strings and numbers in JavaScript, code is executed sequentially. However, real-world JavaScript code often involves interactions with databases, APIs, and files. In many cases, these operations return Promises instead of simple values. A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value, as defined by Mozilla’s website.

It is similar to a situation where we order food at a restaurant. When your order is successfully fulfilled, your server will bring your foods. In other cases, your server may inform you that there was an issue in fulfilling your order, providing reasons such as being out of stock or your server forgetting to place the order. If we make a function returning Promise in JavaScript with this situation, it will look like this below.

Let’s write some code using a real API to better understand Promises. I will use the Random User Generator API with Axios.

Unfortunately, this code returns an error because it takes some time to grab data from the API but your code execute the next line right away.

That’s why we have ‘then’ & ‘catch’ methods in JavaScript. I will rewrite the code like this below which return the data successfully.

We can further enhance this code using the async/await function to make it simpler and more in line with functional programming principles.

That’s it!

Hopefully it helped you understand Promise, and async / await function in JavaScript.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Jake jonggu baek
Jake jonggu baek

No responses yet

Write a response