DEV Community

Marcelle Vargas
Marcelle Vargas

Posted on • Originally published at marcellecode.Medium on

Promises()

According to the MDN Web Docs “ A promise is a proxy for a value not necessarily known “. In other words, a promise is an intermediary between the web application and the server.

How does a Promise work?

To understand how a promise works let’s analyze the fetch function. Fetch is a JavaScript function for performing HTTP requests. And when we make an HTTP request the first thing fetch() returns us is a promise object with a status of pending, because the fetch is making us a “promise” that the request was made and that it will return us with the server’s response.

fetch('https://jsonplaceholder.typicode.com/todos/1') .then( console.log(response.json()))
Enter fullscreen mode Exit fullscreen mode

Then the second return is effectively the server response

fetch('https://jsonplaceholder.typicode.com/todos/1') .then( console.log(response.json())) .then( console.log(json))
Enter fullscreen mode Exit fullscreen mode

Why use?

1- Simplified Error Management: Promises allow you to catch errors in an easier and more organized way compared to nested callbacks. Instead of dealing with multiple levels of nested callbacks, Promises can use a single function catch() to handle all errors in one place.

2- More readability and less nesting: Using Promises can improve code readability as Promises allow code to be written in a more logical and linear sequence rather than using nested callbacks which can make code difficult to read . This can make the code easier to understand and maintain.

3- More modular and reusable code: Promises can be easily used in multiple places in the code and can be chained together to create control flows in a modular way. This makes the code more reusable and easier to maintain and update over time. Additionally, Promises can be used in conjunction with other JavaScript functionality such as async/await to create more efficient and cleaner code.

In other articles we will talk more about synchronous functions with async/await.

Originally published at https://marcellecode.com.

Top comments (0)