Using promises

The traditional way to handle an asynchronous operation is to use callback functions for the success or failure of the operation. One of the callback functions is called, depending on the result of the call. The following example shows the idea of using the callback function:

function doAsyncCall(success, failure) {
// Do some api call
if (SUCCEED)
success(resp);
else
failure(err);
}

success(response) {
// Do something with response
}

failure(error) {
// Handle error
}

doAsyncCall(success, failure);

A promise is an object that represents the result of an asynchronous operation. The use of promises simplifies the code when executing asynchronous calls. Promises are non-blocking.

A promise can be in one of three states:

  • Pending: Initial state
  • Fulfilled: Successful operation
  • Rejected: Failed operation

With promises, we can execute asynchronous calls if the API we are using supports promises. In the next example, the asynchronous call is done and, when the response is returned, the function inside then is executed and takes the response as an argument:

doAsyncCall()
.then(response => // Do something with the response);

You can chain many instances of then together, which means that you can run multiple asynchronous operations one after another:

doAsyncCall()
.then(response => // Get some result from the response)
.then(result => // Do something with the result);

You can also add error handling to promises by using catch():

doAsyncCall()
.then(response => // Get some result from the response)
.then(result => // Do something with result);
.catch(error => console.error(error))

There is a more modern way to handle asynchronous calls, involving async/await, which was introduced in ECMAScript 2017. As yet, it is not as widely supported by browsers as promises. async/await is actually based on the promises. To use async/await, you have to define an async function that can contain await expressions. The following is an example of an asynchronous call with async/await. As you can see, you can write the code in a similar way to synchronous code:

doAsyncCall = async () => {
const response = await fetch('http://someapi.com');
const result = await response.json();
// Do something with the result
}

For error handling, you can use try…catch with async/await, as shown in the following example:

doAsyncCall = async () => {
try {
const response = await fetch('http://someapi.com');
const result = await response.json();
// Do something with the result
}
catch(err) {
console.error(err);
}
}

Now, we can start to learn about the fetch API, which we can use to make requests in our React apps.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.93.136