“This is the fifth day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

1. What is asynchronous

Simply put, it can not be stuck when encountering (network request, scheduled task);

2. The history of asynchronous evolution

Callback functions – > Promise – > Generator – > async/await.

3. Examples of synchronous asynchrony

// async (callback function)
console.log(100)
setTimeout(function(){
  console.log(200)},1000)
console.log(300)    
/ / 100
/ / 300
/ / 200

/ / synchronize
console.log(100)
alert(200)
console.log(300)
/ / 100
/ / 200
/ / 300
Copy the code

4. Asynchronous application scenarios

4.1 Network requests, such as Ajax image loading

// ajax
console.log('start')
$.get('./data1/json'.function(data1){
  console.log(data1)
})
console.log('end')
Copy the code

4.2 Scheduled Task, such as setTimeout

// Image loading
console.log('start')
let img = document.createElement('img')
img.onload = function(){
  console.log('loaded')
}
img.src = '/xxx.png'
console.log('end')
Copy the code

4.3 Event Listening and Binding

// Event listener
document.getElementById('#myDiv').addEventListener('click'.function (e) {
  console.log('I got clicked.')},false);
Copy the code

5. Callback to hell

Callbacks are fine when they have only one level, but with too many nested levels, code readability and maintainability deteriorate.

const https = require('https');


https.get('Destination interface 1'.(res) = > {
  console.log(data)
  https.get('Target interface 2'.(res) = > {
    https.get('Destination interface 3'),  (res) = > {
        console.log(data)
        https.get('Destination interface 4'.(res) = > {
          https.get('Target interface 5'.(res) = > {
            console.log(data)
            .....
            // Endless callback}}}}})Copy the code

6. Typical questions

6.1 Differences between Synchronous and asynchronous

  • JS based is a single threaded language
  • Asynchrony does not block code execution
  • Synchronization blocks code execution

6.2 Loading images asynchronously

function loadImg(src){
    return new promise(
        (resolve,reject) = >{
            const img = document.createElement('img')
            img.onload = () = > {
                resolve(img)
            }
            img.onerror=() = > {
                reject(new Error('Picture load failed'))
            }
            img.src = src
        }
    )
}
const url1 = 'xxx'
const url2 = 'xxx'
loadImg(url).then(img= >{
    console.log(img1.width)
    return img1  // Common objects
}).then(img1= >{
    console.log(img.height)
  	return loadImg(url2)  / / promise
}).then(img2= >{
   	console.log(img2.height)
}).catch(ex= >console.log(ex))
Copy the code

6.3 setTimeout Scenario

// setTimeout
console.log(1)
setTimeout(function(){
  console.log(2)},1000)
console.log(3)
setTimeout(funcion()=>{
  console.log(4)},0)
console.log(5)

//1, 3, 5, 4, 2
Copy the code

6.4 What are the disadvantages of the callback function? How to solve the callback hell problem?

The fatal weakness of Callback functions is that they are easy to write Callback hell. Assuming multiple requests have dependencies, you might write code like this:

ajax(url, () = > {
    // Process logic
    ajax(url1, () = > {
        // Process logic
        ajax(url2, () = > {
            // Process logic})})})Copy the code

The fundamental problem with callback hell is this:

  1. Nested functions are coupled and can be affected by changes
  2. Multiple nested functions make it difficult to handle errors

Of course, callback functions have several other drawbacks, such as the inability to catch errors using a try catch and the inability to return directly.

Solution: Use Promise, which I’ll cover in the next article;

7,

In this article we learned about asynchronous callback asynchronous solutions, and in the next article we will learn more about asynchronous solutions;

Introducing you to Asynchronous Solutions (2)