JavaScript Asynchronization for reading to Tom, and javascript Asynchronization for Tom

Source: Internet
Author: User

JavaScript Asynchronization for reading to Tom, and javascript Asynchronization for Tom

One day, I suddenly wrote a method to call data from the background, which is displayed on the foreground page. However, the output result is always empty and undefined and no data is available. Only when multiple parties looked for information, they found that they had entered the JS asynchronous "pitfall ".

We often hear the concepts of single thread, multithreading, synchronization, and Asynchronization. What are these things?
Let's start with the concepts above.

Basic understanding of single thread, multithreading, synchronization, and Asynchronization

Each running program (that is, a process) has at least one thread, which is called the main thread. The main thread is created when the program is started and used to execute the main function.

1. A single thread is a thread with only one main line. The code runs sequentially from top to bottom. The main thread is responsible for executing all the code of the Program (UI display and refresh, network requests, local storage, etc) [A thread is tired of doing everything]

2. multithreading, as its name implies, is a program with multiple threads that can be created by the user. Several processes created by the user are sub-threads compared to the main thread. The sub-thread and main thread are independent operation units, and their respective operations do not affect each other, so they can be executed concurrently.

Is it a bit dizzy to listen to these dry theories? Coincidentally, I was dizzy at first glance.

While searching for materials, I found someone else's image metaphor.

For example, a single thread is where you go to the kitchen, cook and cook, and one person runs back and forth. A multi-thread is two people, one cooking and one cooking.

Should this be better understood?

What is synchronous and asynchronous?

Let's use a simple example of life.

You can call to book a hotel and ask the staff if they have a room. At this time, the staff needs to check whether there is a room to answer you.

Synchronization means you don't need to wait until the staff tells you whether you have a room.
Asynchronous means hanging up the phone. When you do other things, such as eating and drinking water, the staff will find the information and call to tell you.

So our theme is coming.

What is the asynchronous operation of JS?

The execution environment of JS is single-threaded. That is to say, after the program is executed sequentially, only one task can be executed at a time. If the program wants to run down, it must wait until the current task is completed, no matter how long the current task will be executed (if the program is running out, it is really difficult to wait ).

In order to solve the uncomfortable blocking problem of subsequent programs. JavaScript has an asynchronous processing mode, which is actually latency processing.

Let's throw an example to illustrate it.

var getUserInfo = function () {      $.getJSON("http://www.easy-mock.com/mock/5a09868228b23066479b8379/ajaxData/getUserInfo", function () {        return data;      });    }    var data = getUserInfo();    renderUserInfo(data)

The getUserInfo function is called. It may take a lot of time to retrieve data from the background. This requires renderUserInfo to wait until the data is retrieved. Fortunately, JS has asynchronous operations. When retrieving data, you do not need renderUserInfo to wait for the data to be retrieved, but directly execute it.

In this case, what sequence are the two functions executed? Don't worry, let's debug it:

var getUserInfo = function () {      console.log('aaa');      $.getJSON("http://www.easy-mock.com/mock/5a09868228b23066479b8379/ajaxData/getUserInfo", function () {        console.log('bbb');        return data;      });    }    var data = getUserInfo();    console.log(data);    console.log('ccc');    renderUserInfo(data);

The output after sequential execution was originally thought to be "aaa", "bbb", "ccc", right?

However, things are not that simple. Let's take a look at the console output:


The output result is not sequential.

That is to say, when the function is executed to getJSON to retrieve data, the program does not wait for it to retrieve data and then execute the next step. Instead, it skips the data retrieval phase and directly executes the output data. Therefore, data is also empty.

This is the asynchronous mechanism of JS.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.