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

webpack -v error solution

background I want to check the webpack version, b...

Issues with upgrading Python and installing Mongodb drivers under Centos

Check the Python version python -V If it is below...

Detailed tutorial on installing MySQL 8.0.20 database on CentOS 7

Related reading: MySQL8.0.20 installation tutoria...

MySQL multi-instance deployment and installation guide under Linux

What is MySQL multi-instance Simply put, MySQL mu...

How to Learn Algorithmic Complexity with JavaScript

Table of contents Overview What is Big O notation...

Detailed explanation of the 4 codes that turn the website black, white and gray

The 2008.5.12 Wenchuan earthquake in Sichuan took...

10 Tips for Mobile App User Interface Design

Tip 1: Stay focused The best mobile apps focus on...

nginx+tomcat example of accessing the project through the domain name

I was curious about how to access the project usi...

Solution to Django's inability to access static resources with uwsgi+nginx proxy

When deploying uwsgi+nginx proxy Django, access u...

How to reset the initial value of the auto-increment column in the MySQL table

How to reset the initial value of the auto-increm...

my.cnf (my.ini) important parameter optimization configuration instructions

MyISAM storage engine The MyISAM storage engine i...

Code analysis of user variables in mysql query statements

In the previous article, we introduced the MySQL ...