Asynchronous programming

To put it simply: synchronous execution in your code order, asynchronous execution out of code order, asynchronous execution is more efficient.

Asynchrony is the sending of a child thread from the main thread to complete a task.

Synchronous programming

Strictly follow the order from top to bottom

console.log("Start");
console.log("Show Data");
console.log("End");

/* This is a synchronous code in order to execute */
Copy the code
The callback function

Callback functions exist wherever there is asynchracy in JS.

A callback is a function that tells an asynchronous task what to do when it is finished.

This way the main thread hardly cares about the status of the asynchronous task, and it will finish the task itself.

The asynchronous case

Suppose I want to do three things

Using synchronous programming to do the cleaning first and then do the laundry is very inefficient.

This is what happens when you use a time user to simulate:

setTimeout(() = > {
    console.log("Clean up");
}, 4000);

setTimeout(() = > {
    console.log("Laundry");
}, 3500);

setTimeout(() = > {
    console.log("Cook");
}, 2000);
Copy the code

Waiting for one thing to be done before moving on to the next thing takes too much time and is very inefficient.

OK key point came, I can put the cleaning robot to sweep the floor, clothes to the washing machine, with rice cooker to cook.

And then lie on the couch and play king, and when it’s over tell me to take care of it.

// Use a sweeping robot to do this
function clean(callback) {
    setTimeout(() = > {
        let msg = "Ding, it's clean for you...";
        callback(msg);
    }, 4000);
}


// Give the clothes to the washing machine
function wash(callback) {
    setTimeout(() = > {
        let msg = "Ding, the laundry is done...";
        callback(msg);
    }, 3500);
}

// Leave cooking to the rice cooker
function cook(callback) {
    setTimeout(() = > {
        let msg = "Ding, the rice is ready...";
        callback(msg);
    }, 2000);
}

// The callback function lets you know when the device completes its task
function callback(data) {
    console.log(data);
}


// Get to work
clean(callback);
wash(callback);
cook(callback);


/* >>> Ding, the rice is ready... Ding, the laundry is done... Ding, it's clean for you... * /
Copy the code

Conclusion: See, this is a small case, which uses the callback() function to notify me who completes the task first, even in a real web case.

Suppose I open up a web page and have a lot of images to load… You can’t just wait for one load to finish and go to the next, so whoever finishes first uses the callback function, the callback function

Return the path information of the image, so now that I have the path information of the image,