Simple understanding of asynchrony in Javascript

What is asynchronous?

Asynchrony is relative to synchronization. Synchronization is to execute code line by line. Asynchrony is to execute multiple tasks at the same time.

for instance:

Once in the journey to the west, the boy scolded the monk Tang's teachers and disciples as a bald thief who stole fruit. Sun Wu's face turned red, but he couldn't attack in front of the master, so he was distracted. He pushed down the ginseng fruit tree in the garden without leaving any fruit. When he finished, he took advantage of the night to unlock the door and escaped with the teachers and disciples.

The monkeys here are still being scolded and angry. As a result, they ran to shovel fruit trees separately. This is an asynchronous process.

How is asynchronous implemented?

Isn't javascript single threaded, so how does it achieve asynchrony?

What would you do if the takeout arrived while you were working overtime? Get it yourself, and your work ideas will be interrupted. It's unrealistic to be separated like the monkey king. Fortunately, there is more than one person in the company. We can ask other colleagues to help take it, tell us when we get the takeout, and then we can have a happy meal.

JS is the same. Although it is single threaded and can only handle one thing at the same time, the main thread can initiate an asynchronous request, and the corresponding working thread will receive and process the request. When the processing of the working thread has a result, the browser will notify the main thread that the request has been completed, the result has been obtained, and the callback function can be executed, Process the results obtained asynchronously.

How to write asynchronous code?

The most reasonable way is through Promise objects.

For example, let's see how it works.

My brother-in-law borrowed some money from me last month. When I met him today, I asked him when he could pay back the money. He said he would pay me back when he got his salary next month. I said no, I'm going on a business trip next month. He said: Well, brother-in-law, tell me what you plan to do with this money, and I'll do it for you. Although I doubt it, I can only accept it. After all, I have other things to do. I can't wait for him to change money all the time.
So I said to him: OK. Then next month, you can hand over the money you owe me directly to my wife. My brother-in-law readily agreed.

The above scenario is represented by code, like this:

// Promise object
let Brother in law's promise = new Promise((Promised things) => {
    setTimeout(() => {
        let wages = 2000; // Paid
        let Money to pay back = wages * 0.5; // Take out half to pay the bill
        Promised things(Money to pay back); // Handle the entrustment of my brother-in-law
    }, 30 * 100); // After 30 days
});

// Callback function
function My request(a sum of money) {
    console.log('hold' + a sum of money + 'Give it to your wife');
}

// then specifies the callback function
 Brother in law's promise.then(My request); // My brother-in-law agreed to my request

// Print after 3 seconds: give 1000 to your wife

What is async/await?

JS syntax is just sugar, which can liberate you from callback functions.

Let's take the above situation as an example. If I'm going to take the money for a massage I can't tell my brother-in-law about such things. If my wife knew, she would peel me alive. Then let my brother-in-law directly hit my bank card with the money to be repaid, and I'll wait for the arrival notice of the bank. It doesn't delay my work, and I don't have to tell my brother-in-law my plan, and I can freely arrange the use of funds.

Write code like this:

// Promise object
let Brother in law's promise = new Promise((Promised things) => {
    setTimeout(() => {
        let wages = 2000; // Paid
        let Money to pay back = wages * 0.5; // Take out half to pay the bill
        Promised things(Money to pay back); // Handle the entrustment of my brother-in-law
    }, 30 * 100); // After 30 days
});

// Asynchronous function
async function My plan() {
    // With await, the entrustment becomes: no need to process direct transfer to me
    let a sum of money = await Brother in law's promise; // Waiting for brother-in-law's transfer
    console.log('take' + a sum of money + 'Go get a massage');
};

// Call asynchronous function
 My plan();

// Print in 3 seconds: take 1000 for a massage

Is there any difference between the two writing methods?

They are all based on Promise objects, but one uses the then method to specify the callback function, and the other uses await to obtain the value of resolve (actually the parameter itself). It should be noted that await needs to be written in the asynchronous function (think about why).

Let's do a little exercise to help you understand the difference between the two.

function get(url, callback) {
    var req = new XMLHttpRequest();
    req.open('GET', url, true);
    req.onload = function () {
        if (req.readyState == 4 && req.status == 200) {
            callback(req.response);
        }
    }
    req.send();
}

var url = 'https://miao.baidu.com/';

get(url, function (html) {
    var re = new RegExp('<[^<>]+>', 'g');
    var text = html.replace(re, "");
    console.log(text);
});

// In Miao baidu. Com page in the console
// Print: Hello World

Please refer to the above code and encapsulate a get function with Promise object.

Access Miao. Com through this function baidu. COM and print the text after removing all HTML tags.

Requirements: use then and await methods.

Keywords: Javascript

Added by melkara on Thu, 30 Dec 2021 01:33:46 +0200