16 septiembre, 2024

Promises in JavaScript | Bootcamps

JavaScript is an event-based programming language. This means that it allows us to prepare actions to be executed asynchronously. One of the elements that makes us available to create this asynchrony are promises. In this post, we will teach you What are promises in JavaScript and how they can help us create asynchrony.

What are promises in JavaScript?

Promises in JavaScript are global objects. That is, it is native objects of this programming language that we have access to globally. The main purpose of promises in JavaScript is to create asynchronous actions or schedules. These types of schedules are those actions that we schedule to be executed at some point, depending on when another event happens or even if it happens at all. Therefore, Promises allow us to create actions that are available to be executed immediately, in the future, or never.

Promises in JavaScript are made up of several fundamental elements. Primarily, a promise has a callbackwhich means that We must pass it a function to execute.

Remember that when we pass a function as a parameter to a method, it is called callback. To learn more about this concept, you can read our posts about what are callbacks in JavaScript and how to use them.

The same thing happens in JavaScript promises as with the method reduces. In both scenarios, we use a function callback to which we must pass two parameters. In the case of the method reduces, we must pass the parameters of previousValue and currentValue. For a promise, we must pass the parameters solve and decline. The particularity of this context is that the parameters solve and decline They are, in turn, functions.

What do promises look like in JavaScript?

To better understand the concept of promises in JavaScript, we give you an example. Next, you will see a promise that is part of the function do you love me. This promise creates a console.log with which he paints the message ‘Let me think about it’ on the screen. Then, use the method setTimeout to control the time after which the other contained actions will occur.

function doYouLoveMe(name) {

return new Promise (function (resolve, reject) {

console.log (‘Let me think about it…’)

setTimeOut (() => {

if (name = ‘Alberto’) {

resolve (‘Yes!’)

} else {

reject (‘Sorry but no…’)

}

}, 1000)

})

The method setTimeout It is part of the methods available in JavaScript to control the time of the actions to be executed. This method, like promises, allows us to create asynchrony, that is, prepare actions for cases in which they must be executed, but which are not immediate. To learn more about this method, we invite you to read our article on the methods setTimeout and setInterval in JavaScript.

The promise you just saw has defined, inside the method setTimeout, two possible actions. If the function name do you love me is ‘Alberto’, the returned promise is resolved with the string ‘Forks!’. If the name is not ‘Alberto’, the function will reject the promise and return the string ‘Sorry but no…’.

What does this mean about resolving or rejecting promises in JavaScript? These two parameters or functions inside the promises They refer to the possible states within this object. Promises in JavaScript are objects that represent operations that have not yet been completed. Therefore, in the previous example we simulate this state earring with the method setTimeout.

Keep in mind that promises, in addition to the state earring, They can exist in two more states. To learn more about this topic, we invite you to read our post on promise states in JavaScript.

Then, since the promises are to be completed later, What we do is define its behavior in case it goes well and in case it goes wrong. In this sense, promises allow us to prepare actions to be executed according to the scenario that takes place, whenever it takes place. Thus, They are essential to create asynchrony in JavaScript.

Although the parameters resolve and reject They allow us to prepare these actions for any scenario, we can create promises in JavaScript without calling both functions. That is, we can create an object promise without calling the function reject or to the function resolve.

Practical example with promises in JavaScript

Promises are a concept that It allows us to handle asynchronous processes in this programming language. That is, those processes that we do not know how long they will take or what response they will give us. So, promises (defined by the object promise in JavaScript), allow us to prepare code in case, when the process ends, we obtain a satisfactory or unsatisfactory response.

A practical example with promises in JavaScript is Think about a request that our mother makes of us. So, let’s suppose that she, thinking about today’s dinner, has asked us to go get potatoes. This is a request that can be considered an asynchronous process, since our mother does not know how long it will take us to go get potatoes or if we will find them. We also don’t know the details behind this request, we don’t know if we are going to find a parking space or if the store is going to be open. However, this does not matter to us, We only care about the result of the promise.

Following this logic, we can declare a function called goForPotatoes to give us back a promise. This promise will then have two options: the case in which we get potatoes and the case in which we don’t get them. In the first scenario, the promise completes (goes to state fulfilled) and in the second it is rejected (it goes to the state rejected). We could also consider a third scenario: the case in which we do not return. In this scenario, the promise would remain eternally in the state pending.

Now, There are two methods that allow us to go from pending to the different states. The method resolve helps us declare what must happen for a promise to be completed. For its part, the method reject It allows us to declare what must happen for the promise to be rejected.

Let’s write some pseudocode following our example and the previous methods:

function goForPotatoes ( ) {

return new Promise (function (resolve, reject) {

const there arePotatoes = searchPotatoesIn3Sites ( )

if (there arePotatoes) {

resolve (‘🥔 🥔’)

} else {

reject(‘😔 😔‘)

}

})

}

In the previous lines of code, we have defined an asynchronous function called goForPotatoes. This function returns a new instance of the object promise. Then define a constant there arepotatoes which is the same as searchingPotatoesIn3Sites. Finally, using a conditional, solve the promise when we find potatoes. If this scenario does not happen, the promise is rejected.

Do you want to continue learning?

Now that you know how promises work in JavaScript, in We are sure that you want to continue learning about what you can do with this programming language. To do this, we recommend taking a look at our Full Stack Web Development Bootcamp program, where you will learn everything you need to be an expert in web development. In a few months, you will master languages ​​​​such as JavaScript, CSS and HTML. Do you want to continue learning both theoretically and practically? Enroll now!

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *