A brief discussion on the three major issues of JS: asynchrony and single thread

A brief discussion on the three major issues of JS: asynchrony and single thread

Single thread

However, when we encounter network requests or scheduled tasks during development, if we wait for the network request to end or the scheduled task to end before doing other things, the page will be stuck, so js has an asynchronous mechanism to solve this problem.

asynchronous

The characteristic of asynchrony is that it will not block the execution of subsequent code. The asynchronous task will be executed after the synchronous task is completed. In contrast, synchronization blocks code execution. The applications of asynchronous tasks mainly include network requests and scheduled tasks.

Asynchrony is achieved through callbacks, and asynchronous execution code is executed in callbacks. However, there are some scenarios, such as we have three network requests abc that need to be executed in sequence. Initiate request b in the callback of a, and initiate request c in the callback of b. This will cause a very confusing writing method, which is called callback hell. Imagine that if the page logic is too complicated and needs to call 10 interfaces in sequence, the readability of the code will be very, very poor. If we see this kind of code from others, we can't help but feel a thousand beasts running in our hearts.

Basic usage of promise:

let fun1 = function(flag){
    return new Promise((resolve,reject)=>{
    if(flag){
        setTimeout(() => {
        resolve("success")
        }, 1000);
    }else{
        setTimeout(() => {
        reject("fail")
        }, 1000);
    }
    })
}
 
 fun1(true).then((res)=>{
    console.log(res) //success
}).catch((res)=>{
    console.log(res)
})
fun1(false).then((res)=>{
    console.log(res)
}).catch((res)=>{
    console.log(res) //fail
})

The above is the simplest promise function. The promise function returns a Promise object. The parameter is a function that receives two parameters, resolve and reject. These two parameters are also functions. When resolve() or reject() is executed, the function returns.

If resolve() is executed, the then() method will be executed when called and receive the parameters returned by resolve();

If reject() is executed, the catch() method will be executed when called and receive the parameters returned by reject();

Use promise to re-implement the above three network request problems:

let callService = function(url){
      return new Promise((resolve,reject)=>{
          axios.get(url).then((res)=>{
            resolve(res)
          }).catch((err)=>{
            reject(err)
          })
      
      })
    }
    const url1 = "/user/url1"
    const url2 = "/user/url2"
    const url3 = "/user/url3"
    callService(url1).then((res)=>{
      // do something
      return callService(url2)
    }).then(()=>{
      // do something
      return callService(url3)
    }).then((res)=>{
      // do something
    }).catch((err)=>{
      console.log(err)
    })

After re-implementing it using the above method, there will only be one layer of writing, and you will not fall into layers of callbacks.

promise.all

promise.all can wrap multiple promises into a new instance, returning an array when successful and the value of the one that fails first.

The promise.all method can help us deal with the problem of calling multiple interfaces simultaneously in daily development.

let p1 = new Promise((resolve, reject) => {
  resolve('successful')
})

let p2 = new Promise((resolve, reject) => {
  resolve('success')
})

Promise.all([p1, p2]).then((result) => {
  console.log(result) //['success', 'success']
}).catch((error) => {
  console.log(error)
})

promise.race

The function of this method is to run multiple interfaces in a race, and return the one that runs faster.

Promise.race([p1, p2]).then((result) => {
  console.log(result)
}).catch((error) => {
  console.log(error) 
})

The above is a brief discussion of the details of the three major JS mountains: asynchrony and single-threading. For more information about the three major JS mountains: asynchrony and single-threading, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • JavaScript single thread and asynchronous details
  • Detailed explanation of asynchronous process implementation in single-threaded JavaScript
  • Analyze the characteristics of JS single-threaded asynchronous io callback
  • JavaScript's Three Mountains: Single Thread and Asynchronous

<<:  Detailed explanation of MySQL InnoDB secondary index sorting example

>>:  Detailed installation and configuration tutorial of PostgreSQL 11 under CentOS7

Recommend

JavaScript Basics Operators

Table of contents 1. Operators Summarize 1. Opera...

Summary of problems encountered when installing docker on win10 home version

Docker download address: http://get.daocloud.io/#...

How to quickly deploy Redis as a Docker container

Table of contents getting Started Data storage Co...

How to use physics engine joints in CocosCreator

Table of contents mousejoint mouse joint distance...

MySQL import and export backup details

Table of contents 1. Detailed explanation of MySQ...

Detailed explanation of routes configuration of Vue-Router

Table of contents introduce Object attributes in ...

DockerToolBox file mounting implementation code

When using docker, you may find that the file can...

Solutions to VMware workstation virtual machine compatibility issues

How to solve VMware workstation virtual machine c...

Node.js returns different data according to different request paths.

Table of contents 1. Learn to return different da...

How to query duplicate data in mysql table

INSERT INTO hk_test(username, passwd) VALUES (...

MySQL 8.0.16 installation and configuration graphic tutorial under macOS

This article shares the installation and configur...

SQL Practice Exercise: Online Mall Database User Information Data Operation

Online shopping mall database-user information da...

Detailed explanation of Vue's list rendering

Table of contents 1. v-for: traverse array conten...