paint-brush
Understanding Promises in JavaScriptby@bormando
503 reads
503 reads

Understanding Promises in JavaScript

by Dmitrii BormotovMarch 7th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Promise is an object in JavaScript which may have different states and return different values. Use async/await or .then() to wait for promises to resolve. Asynchronous construction is most preferable within developers community.
featured image - Understanding Promises in JavaScript
Dmitrii Bormotov HackerNoon profile picture

Hello everyone!


I was inspired to write this article by my students and mentees. There are a lot of articles like this across the internet, but I dedicate this one to beginners (specifically for those, who need to know the basics only).


You’ll find this article useful if you’re beginning your journey as a QA Automation Engineer.


IMPORTANT: This is not a complete guide on asynchronous functions and promises. If you’d like to know more - better check out the mdn web docs.

What’s Promise?

Speaking technically, Promise is an object. It represents the eventual completion (or failure) of an asynchronous operation and its resulting value.


The best example of a Promise object is an HTTP request:


Sending an HTTP request in Postman


When you send a request - it takes some time for a server to process it (which means that we don’t get the response from the server immediately).


Server responded to the request


Once the server has processed the request - we receive a response from it. As you can see in the screenshot - it took ~3 seconds for the server to respond.

HOW Does it Work in Javascript?

So, if we’d execute a JavaScript function fetch to get the response - we won’t get it immediately as well.


I.e., the fetch function will return a Promise, instead of a response:


fetch function returned a Promise


From a JavaScript perspective - it got the job done (the request is sent, isn’t it?).


If we’d take a look at the fetch function - we’ll see that it’s a function that returns a Promise<Response>:


fetch function type declaration


It means that this function returns a Promise (of course). But if we’ll wait for Promise to resolve - it’ll return a Response object!


How do we wait? Well, there are 2 ways to do that…

Synchronous Code

Use then function:


fetch and following then function


then function receives a resolved object (Response in the current example) - i.e., whatever Promise<something> got inside <>.

Asynchronous Code

Use async / await:


await expression in async function


How is that different than something we’ve done in the synchronous (sync) example?


  1. You don’t need .then() function to extract a value from the async (fetch) function.


  2. await keyword is available in async functions only.


  3. If you won’t use await word in asynchronous functions (the ones that return Promise objects) - they will run simultaneously.

Running Code Asynchronously

async / await and then() syntax seems redundant in most of the use cases if you’re the one who develops automated tests. Why does this syntax even exist? What’s the point of this? Why can’t we just receive a value that we need from a function?


The answer is simple - it allows us to define functions without the strict sequence of commands.


I.e., what if we need to execute 10 requests, but they don’t have to be run synchronously (one after another)?


Promise.all([
  fetch(...),
  fetch(...),
  ...
]).then((responses) => {
    responses.forEach(value => console.log(value))
  })


The code above will run all fetch commands inside of Promise.all([]), and then wait for them to resolve (finish) and log into the console every response.


OR you can do the same with async/await construction:


const [responses] = await Promise.all([
  fetch(...),
  fetch(...),
  ...
])

responses.forEach(value => console.log(value))

Conclusion

Now you know the basics of Promise object usage, and it’ll be good enough for most of the use cases, especially if you’re working with automated tests.


Also, keep in mind that most developers use async / await construction instead of sync (i.e., .then()) as it’s supposed to be “a syntax sugar”.


Thanks for reading! Hope you’ve learned something new today 🤓