Implement promises: resolve / reject

How-to article to explain some ECMAScript 2015 promise implementation code, and the resolve and reject functions.

In a previous installment of we talked about promises and explained how they can help us organize our code. We saw that in the Javascript language it is easy to fall into what is known as “spaghetti code” and that promises offer us an excellent way to organize our code avoiding the pyramid of callbacks. You can check the .

On this occasion we are going to expand the information regarding the implementation of a function that returns a promise, treating both positive cases (success) and negative cases (failure). We will also delve into other important information about the Javascript language and the new Ajax resource access API: fetch.

resolve and reject functions

When we implement a function that returns a promise, we have two functions available to us that allow control to be returned to the code that called the promise. Those functions return data when the promise executed normally and produced the expected results, and when the promise failed or was unable to achieve the desired results.

The code for a function that returns a promise has an initial form like this:

function returnsPromise() { return new Promise( (resolve, reject) => { //we perform our operation… }) }

As you can see, this code returns a new promise. To create the promise we use “new Promise”. We feed the promise constructor with a function that receives two parameters: resolve and reject, which are in turn functions that we can use to return values ​​in both the positive and negative cases.

See also  Web Developer, extension for Firefox

Note: Obviously you can call these parameters however you want, since they are just parameters, but the names indicated already tell us what each one is for.

Now let’s look at our operation, which could have a form like this:

function returnsPromise() { return new Promise( (resolve, reject) => { setTimeout(() => { let allRight = true; if (allRight) { resolve(‘Everything went well’); } else { reject(‘ Something has gone wrong) } }, 2000) }) }

In our code we will carry out any type of process, generally asynchronous, so it will have an execution time during which control will be returned by means of a callback function. In the callback function we will be able to know if that process occurred correctly or not. If it was correct, we will use the resolve() function, sending back as a parameter the value that has been obtained as a result. If something failed we will use the reject() function, sending the reason for the error.

We can use that function that returns the promise with code like this:

returnsPromise() .then( response => console.log(response) ) .catch( error => console.log(error) )

As you might already guess, then() receives the response indicated in the resolve() and catch() the error indicated in the reject.

How to implement an Ajax connection with fetch that returns a text

In it we saw that it is a new working model with Ajax, but using promises. We saw that a fetch() returns a response from the server, with data about the HTTP request, but if we wanted to access the text of the response, we needed to chain a second promise, calling the text() method on the response. That second promise made the code a bit more complicated for something as simple as it is: given a URL, receive the text that is in the resource.

See also  What is a Webmaster

Next we are going to put an alternative code, which performs both promises and directly returns the response text. Since this is asynchronous code, which will take a while to execute, and after that you must return control to the original script, we will implement it via a promise.

function getText(url) { return new Promise( (resolve, reject) => { fetch(url) .then(response => { if(response.ok) { return response.text(); } reject(‘No was able to access that resource. Status: ‘ + response.status); }) .then( text => resolve(text) ) .catch (err => reject(err) ); }); }

This code uses the promise chaining model, executing asynchronous operations, one after the previous one finishes.

We start by fetch()ing a URL that we receive as a parameter. That fetch returns a promise, which when executed successfully gives us the response from the server.

If the response was ok (response.ok is true) then it returns a new promise delivered by execution of the response.text() function. If the response wasn’t right, then we reject the promise with reject(), indicating the reason why we’re rejecting with an error.

In turn, the response.text() code, which returned another promise, can give a success or an error case. The success case is treated with the second then(), in which we accept the promise with the resolve.

Both for the case of an error in fetch() and an error case in the text() method, as well as for any other detected error (even badly written code) we perform the corresponding catch(), rejecting our original promise.

Note: Note that a single catch() is used to detect any type of error, both in the first promise (fetch) and in the second (text).

See also  How to interpret line breaks as BR in HTML?

You can use this code in the following way. You will see that we have a single method that returns the text directly to us.

getText(‘test.txt’) .then( text => console.log(text) ) .catch( err => console.log(‘ERROR’, err) )

Loading Facebook Comments ...
Loading Disqus Comments ...