Using promises

Promises provide a simple syntax for handling these resolve and reject functions. Let's take a look at how we would use the promises defined in our previous code snippet, as follows:

function callDelayedPromise() { 
    console.log(`calling delayedPromise`); 
    delayedPromise().then( 
        () => { console.log(`delayedPromise.then()`) } 
    ); 
} 
 
callDelayedPromise(); 

Here, we have defined a function named callDelayedPromise. This function logs a message to the console, and then calls our delayedPromise function. We are using fluent syntax to attach to the then function of the promise, and defining an anonymous function that will be called when the promise is resolved. The output of this code is as follows:

calling delayedPromise
delayedPromise.then()

This promise fluent syntax also defines a catch function that is used for error handling. Consider the following promise definition:

function errorPromise() : Promise<void> { 
    return new Promise<void>  
    ( 
        (   resolve: () => void,  
            reject: () => void 
        ) => { 
          reject(); 
             }   
    ); 
}

Here, we have defined a function named errorPromise using our promise syntax. Note that within the body of the promise function, we are calling the reject callback function instead of the resolve function. This reject function is used to indicate an error. Let's now use the catch function to trap this error, as follows:

function callErrorPromise() { 
    console.log(`calling errorPromise`); 
    errorPromise().then( 
        () => { console.log(`no error.`) } 
    ).catch( 
        () => { console.log(`an error occurred`)} 
    ); 
} 
 
callErrorPromise(); 

Here, we have defined a function named callErrorPromise that is logging a message to the console, and then invoking the errorPromise promise. Using our fluent syntax, we have defined an anonymous function to be called within the then response (that is, on success), and we have also defined an anonymous function to be called within the catch response (that is, on error). The output of this code is as follows:

calling errorPromise
an error occurred  
..................Content has been hidden....................

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