Promises()
Marcelle Vargas
Posted on March 28, 2023
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()))
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))
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.
Posted on March 28, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024