promise and asynchronous programming

Posted by rashu.dr on Tue, 07 Dec 2021 17:08:50 +0100

promise introduction

Promise is a solution for asynchronous programming, which is more reasonable than traditional solutions (callback functions and events).

What is synchronization?

After the current call is issued, subsequent code cannot be executed before the result is received, and the subsequent code is always online waiting, and synchronization is blocked.

Code demonstration: (1) use alert to introduce synchronous blocking (2) use the function to calculate the sum of two numbers and receive them with variables after calling

cript>
        //Synchronization code:
         console.log(111);
         demo();

         function demo() {
             console.log(222);
            alert('Hello');
         }

         console.log(333);
    </script>
//Output result: 111 222 333

What is asynchronous?

The current call is generated before the result can be executed without the result. The result of the current call will notify the caller in the way of notification, callback function, and asynchronous is non blocking.

Common application scenarios: (1) network request (2) reading file (3) event function in JS is a very typical asynchronous expression.

Code demonstration: use timer to simulate asynchronous and feel the characteristics of asynchronous programming.

<script>

        //Asynchronous code:
        console.log(11);

        let fn = function(d) {
            console.log(d, 888);
        }
        test(fn);

        function test(calls) {
            //console.log(calls);
            setTimeout(() => {
                // console.log(22);
                //Demand: return 22
                calls(22);
            }, 2000);
        }
        console.log(33);


      
    </script>
//Output results: (11) (33) (22 888)

Callback function

When using JavaScript, in order to implement some logic, layers of nested callback functions are often written. If nested too much, it will greatly affect the code readability and logic. This situation is called callback hell (or callback). Often, some asynchronous operations need to use callback functions to get the results

promise

promise introduction

Promise is a solution to asynchronous programming. It is a container that holds an event that will end in the future. Promise is one of the asynchronous programming solutions. Promise is actually a promise. Promise usually contains asynchronous codes to be executed in the future, and these asynchronous codes will have two results after execution: success or failure,

Therefore, Promise has three states: 1. Pending (initial state)

                                          2. Fully filled / resolved

                                            three   Rejected (failed status)

When we call the callback function on success (resolve() method) inside Promise, we convert the initial state of Promise to the success state, and execute the callback function on success defined in then() method;

When we call the callback function in case of failure (reject() method) inside Promise, we convert the initial state of Promise to the failure state, and execute the callback function in case of failure defined in then() method or catch() method

Promise features:

1) The internal code of Promise is executed synchronously;

<script>
        console.log(111);
        let prm = new Promise(function() {
            console.log(22);
        });
        console.log(333);
    </script>

2) . when the callback function at the time of success is called inside Promise, the callback function at the time of success defined in the first then() method will be executed. When the callback function at the time of success in the first then() method is completed, the success status will be returned. The callback function at the time of success in each subsequent then() method will be called automatically;

3) It is meaningful to call multiple then() methods, while the catch() method can be called once;

4) . by returning a specific value or a Promise object in the success callback function in the then() method, the specific value or the result of the success callback function in the Promise can be passed to the success callback function in the next then() method;

Basic syntax:

new Promise( (resolve,reject)=>{
        //  resolve()
    	//  reject()
} )

  promise status

Promise container: promise itself is not asynchronous. What you promise is what will happen in the future

promise often encapsulates an asynchronous task internally

promise object method

then

romise object.then( (result)=>{
   //Code block
} )

catch

promise object.catch( (abnormal)=>{
   //Code block
} )

Code case:

      //resolve: callback function to execute when successful
        //reject: callback function to execute when failure occurs
        let prm = new Promise((resolve, reject) => {
           setTimeout(() => {   
             if (true) {
                   resolve(111); //Call function
              } else {
                  reject('Failure reason'); //Call function
              }
  
              }, 2000);
      });
        // 1.
       // prm.then(function(d) {
        //     console.log(` succeeded: ${d} ');
        // }, function(err) {
        //     console.log(` failed: ${err} ');
        // });

         // 2.
       prm.then(function(d) {
           console.log(`succeed:${d}`);
       }, function(err) {
           console.log(`failed:${err}`);
       });
    </script>
Output results:Succeeded 111 (here, the program is executed when successful: resolve)

Note:

1. We can define the callback methods to be executed when resolve succeeds and reject fails in the then method  

2. You can also define the callback method on success in the then method and the failure in the catch method

call chaining

Note: it makes sense to call multiple then() methods, while the catch() method can be called once;

If the callback function in the then() method returns a specific value or a Promise object, the specific value or the result of the callback function in the Promise can be passed to the callback function in the next then() method;

Code case:

<script>
        let prm = new Promise((resolve, reject) => {
            if (1) {
                // if (0) {
                resolve('success');
            } else {
                reject('failed');
            }
        });

         prm.then(d => {
             console.log(d, 111);
             return 'Yes OK'
         }).then(d2 => {
             console.log(d2, 222);
             return 'Hello'
         }).then(d3 => {
             console.log(d3, 333);
         }).catch(e => {
             console.log(e);
         });
</script>

  Output result: the result of the callback function on success in Promise is passed to the callback function on success in the next then() method

 

 

Promise.all() concurrency method:

Promise.all(): concurrent method. Concurrency refers to executing multiple different tasks at the same time point.

Method is used to wrap multiple Promise instances into a new Promise instance

Syntax of the all() method:

Promise.all( [ promise Example 1,promise Example 2,... ] )

Features of all() method:

1) If all Promise instances in all() are executed successfully, the returned result is an array, and each value in the array corresponds to the Promise instance in all() method one by one;

Code case:

<script>
        function demo() {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    if (1) {                    // Callback function on successful call
                        resolve('Hello');
                    } else {
                        reject('Failed 1');
                    }

                }, 3000);

            });
        }

        function test() {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                  
                    if (1) {                   // Callback function on successful call
                        resolve('123');
                    } else {
                        reject('Fail 2');
                    }

                }, 2000);

            });
        }


       let prm = Promise.all([demo(), test()]);
        prm.then(d => {
            console.log(d, 111111);
        }).catch(e => {
            console.log(e, 222222);
        });
    </script>

  The result is as shown in the figure: an array is returned, and each value corresponds to the Promise instance in the all() method one by one;

 

 

2) The Promise instances in. all() either execute successfully or fail. If the execution fails, the result of the first failed Promise instance will be returned;

Code case:

<script>
        function demo() {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    if (0) {                      // Callback function on call failure
                        resolve('Hello');
                    } else {
                        reject('Failed 1');
                    }

                }, 3000);

            });
        }

        function test() {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                  
                    if (0) {                    // Callback function on call failure
                        resolve('123');
                    } else {
                        reject('Fail 2');
                    }

                }, 2000);

            });
        }

        let prm = Promise.all([test(), demo()]);
        // console.log(prm);
        prm.then(d => {
            console.log(d, 1111111);
        }).catch(e => {
            console.log(e, 2222222);
        });
    </script>
//The output result failed 2222222 because the test() we called first returned the result of the Promise instance that failed first;

Topics: Javascript node.js Front-end ECMAScript