Promise of “top speed typescript”

Time:2021-11-29
[TOC]

1、 Asynchronous programming

  1. Concept of asynchronous programming: asynchronous programming (async) is relative to synchronous programming (sync); We are learning that in traditional single thread programming, the running programs are executed synchronously(be careful:Synchronization does not mean that all steps run at the same time, but that steps are executed sequentially in a control flow sequence), while the concept of asynchrony does not guarantee synchronization, that is, the execution of an asynchronous process will no longer have a sequential relationship with the original sequence.

The simple explanation is: synchronization is executed in the order of your code, while asynchronous is not executed in the order of your code. Asynchronous execution will be more efficient.

  1. When to use asynchronous programming: in front-end programming (even the back-end sometimes), when we deal with some short and fast operations, such as calculating the result of 1 + 1, we can often complete it in the main thread. As a thread, the main thread cannot accept multiple requests at the same time. Therefore, when an event does not end, the interface will not be able to process other requests.

    Now there is a button. If we set its onclick event as an endless loop, the whole web page will lose response when this button is pressed.

    In order to avoid this situation, we often use sub threads to complete things that may take long enough to be noticed by users, such as reading a large file or making a network request. Because the child thread is independent of the main thread, even if it is blocked, it will not affect the operation of the main thread. However, the sub thread has one limitation: once it is launched, it will lose synchronization with the main thread. We can’t determine its end. If we need to deal with some things after the end, such as processing information from the server, we can’t merge it into the main thread.

    In order to solve this problem, asynchronous operation functions in JavaScript often realize the result processing of asynchronous tasks through callback functions.

2、 Promise

  1. Construct promise:

    Now let’s construct a promise class

    function Promise (function(resolve, reject){
      //What to do
    })

    When we encounter some asynchronous tasks, if it’s OK once, what if it’s multiple times? For example, now we need to output the string three times, with an interval of 1 second for the first time, 4 seconds for the second time, and 3 seconds for the third time. Before that, we implemented it as follows:

    setTimeout(function (){
      console.log('Frist')
      setTimeout(function (){
        console.log('Second')
        setTimeout(function (){
          console.log('Thirt')
        },3000)
      }, 4000)
    }, 1000)

    Look carefully at whether the code is very complex. This program has completed our purpose. It can be seen that maintenance is a very cumbersome thing.

    Now we use promise to realize:

    new Promise(function(resolve, reject){
      setTimeout(function(){
        console.log('Frist')
        resolve()
      }, 1000)
    }).then(function(){
      return new Promise(function(resolve, reject){
       setTimeout(function(){
        console.log('Second')
        resolve()
      }, 4000)
    }).then(function(){
        return new Promise(function(resolve, reject){
         setTimeout(function(){
           console.log('Thirt')
           resolve()
        }, 3000)
      })

    In fact, this code is still very long and difficult to understand. We don’t need to understand it here

    1. Use of promis:

      For example, we still use the above timer. Promise is only a function, and its parameters are also a function,new Promise(function (resolve, reject)The parameters in promise function are also functions, that is:resolve()andreject()When promise is constructed, the starting function is executed asynchronously and the function is calledresolve(res)Indicates that everything is running normally and willresTo the next call; Call functionreject()Indicates an exception occurred.

      new Promise(function (resolve, reject) {
          var a = 0
          var b = 1
          if (b === 0) {
            reject("Divide zero")
          }else {
            resolve(a / b)
          }
      }).then(function (value) {
          console.log("a / b = " + value);
      }).catch(function (err) {
          console.log(err)
      }).finally(function () {
          console.log("End")
      })

      Program output results:

      a / b = 0
      End

      here:

      Function(). Then (function (RES)) // the res in the last called resolve (RES) will be given to res
      Function(). Catch (function (RES)) // the res in the reject (RES) of the last call will be given to res, and the error we handled in advance will be returned to res, so that the program will not hang up

      However, please note the following two points:

      • The scope of resolve and reject is only the start function, excluding then and other sequences;

      • Resolve and reject cannot stop the start function. Don’t forget to return.

      Here is a complete supplement: the promise class has three methods. Then (). Catch () and. Finally (). The parameters of these three methods are a function,. Then () can add the functions in the parameters to the normal execution sequence of the current promise,. Catch () sets the exception handling sequence of promise, and. Finally () is the sequence that must be executed at the end of promise execution The functions passed in by then () will be executed in sequence, and any exception will directly jump to the catch sequence:

new Promise(function (resolve, reject) {
      console.log(1111)
      resolve(2222)
  }).then(function (value) {
      console.log(value)
      return 3333
  }).then(function (value) {
      console.log(value)
      throw "An error"
  }).catch(function (err) {
      console.log(err)
  });

  Output:
  1111
  2222
  3333
  An error

3、 Promise function

  1. Implementation of promise timer

function print(delay, message):Promise<string>{
  return new Promise((resolve, reject)=>{
      setTimeout(()=>{
            console.log('message')
       resolve()
  }, delay)
 })
}

Call:

print(1000, 'Frist').then(()=>{
  return print(4000, 'second').then(res=>{
    return print(3000, 'Thirt').then(res=>{
      consoloe.log('End')
    })
  })
})

Output:

"message:",  "frist" 
"message:",  "second" 
"message:",  "thirt" 
 "end" 
  1. Callback of addition + multiplication

    //Return promise < number > type
    function add(a: number, b: number): Promise<number> {
        console.log('start promise')
        //The parameter of promise is a function with two functions as parameters: function: (resolve, reject)
        return new Promise((resolve, reject) =>{
            If (B% 17 = = = 0) {// find the module of 17 here,
                return reject(`bad number: ${b}`)
            }
            //SetTimeout (function:, timeout?) system function,
            setTimeout(()=>{
                //We don't need to know what resolve is
                resolve(a + b)
            }, 2000)
        })
    }

    Call:

    add(2, 3).then(res =>{
        console.log('2 + 3', res)
        resolve(res)
        return add(res, 4).then(res =>){
            console.log('2 + 3 + 4', res)                    
            }
          }
    2 + 3, 5
    2 + 3 + 4, 9

    Multiplication:

    
    function mul(a: number, b: number): Promise<number> {
        return new Promise((resolve, reject) =>{
            setTimeout(()=>{
                 resolve(a * b)
            }, 3000)
        })
    }

    Call:

    //(2 + 3) * 4 + 4
    add(2, 3).then(res =>{
        console.log(res)
        return mul(res, 4).then(res =>{
            console.log(res)
            return add(res, 5).then(res =>{
                console.log('(2 + 3) * 4 + 4', res)
            }).catch(err =>{
                console.log('cauht err')
            })
        })
    })

    Output:

    5
    20
    (2 + 3) * 4 + 4, 24

4、 Promise handles multitasking

We often process multiple tasks in the network at the same time, which is also the real meaning of promise. Now let’s take a look at the simple processing of multiple tasks:Promise.all()Method returns the result of the corresponding operation in the form of an array

//Processing multiple requests
//(2 + 3) * (4 + 4) * (20 + 21)
//Promise. All() returns an array corresponding to the number of parameters
Promise.all([add(2, 3), add(4, 4)]).then(res =>{
    res[0], res[1]  //const [a, b, c] = res
    console.log(res[0], res[1])  
    return mul(res[0], res[1], ).then(res =>{
        console.log('(2 + 3) * (4 + 4)=',res)
    })
})

Output:

(2 + 3) * (4 + 4)=, 40

Here is another method:Promise.race()Multiple parameters are passed in, only one result is returned, and it is the fastest result

Promise.race([add(2, 3), add(4, 4)]).then(res =>{
    console.log(res)
})

Output:

5

5、 Async / awai syntax

In TS, we can useasync/awaiTo simplify our code above and make our code more intuitive.
This is what we did before:

//(2 + 3) * 4 + 4
add(2, 3).then(res =>{
    console.log(res)
    return mul(res, 4).then(res =>{
        console.log(res)
        return add(res, 5).then(res =>{
            console.log('(2 + 3) * 4 + 4', res)
        }).catch(err =>{
        console.log('cauht err')
        })
    })
})

We useasync/awaiThen it was like this

//(2 + 3)  *  (3 + 4)
async  function calc(){
    try{
        const [a, b] = await  Promise.all([add(2, 3), add(3, 4)])
        console.log('2 + 3:', a)
        console.log('3 + 4:', b)
        return  await mul(a, b)
    }catch(err){
        console.log('catch err', err)
        return  undefined
     }
}

Note here:

async function func_name(){
    await ...
}

asyncIt needs to be used before the field defined by the function
awaitMust be used in a function

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

On the mutation mechanism of Clickhouse (with source code analysis)

Recently studied a bit of CH code.I found an interesting word, mutation.The word Google has the meaning of mutation, but more relevant articles translate this as “revision”. The previous article analyzed background_ pool_ Size parameter.This parameter is related to the background asynchronous worker pool merge.The asynchronous merge and mutation work in Clickhouse kernel is completed […]