The promise class

Before introducing async, let's discuss a little about the native Promise class in JavaScript. As mentioned, promises are the way modern JavaScript manages asynchronous actions. The standard Promise class can be used for creating promises. A promise can be defined as seen in the following code snippet:

const dataPromise = new Promise((resolve, reject) => resolve("some important data!"));

From the preceding code block, we can see that a function is passed to the Promise constructor—this function is called an executor function. This executor has two arguments passed into it, which are used to determine two important properties of the resulting promise—its state and result properties.

The default value of state is pending, which then changes to either fulfilled or rejected. The default value of result is undefined, which then changes to any value of your choosing.

The two functions an executor receives as arguments are resolve(value) and reject(error). The resolve(value) function indicates that the promise was successfully completed, and hence it sets the state of the promise to fulfilled and assigns value to its result property. The reject function indicates that a promise failed (an error occurred) and accordingly sets the state propertyof the promise to rejected and assigns  error to its result property.

The result of the promise defined previously can be obtained using its .then() function, as seen here:

dataPromise()
.then(data => console.log(`Here is ${data}`));

// Here is some important data!

In the case of failures, promises can also be rejected in a like manner. Here's a promise definition that throws an error or rejection:

const dataPromise = new Promise((resolve, reject) => reject(new Error('data failure!')));

When retrieving results for the previous promise, the error can be handled with the .catch() function:

dataPromise()
.catch(error => console.log(`Data retrieval failed. ${error}`));

// Data retrieval failed. Error: data failure!
..................Content has been hidden....................

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