Asynchronous concept of "go" javascript

Source: Internet
Author: User

One day suddenly wrote a method to call data from the background, displayed in the foreground page, but the output is always empty undefined, no data. Multi-party find data only found that the original is into the JS asynchronous "pit."

We often hear the concepts of single-threaded, multithreaded, synchronous, asynchronous, what exactly are these things? So let's start with the above-mentioned concepts O ( ̄▽ ̄) ブ

Basic understanding of single-threaded, multi-threading, synchronous, asynchronous

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

    • A single thread is just one mainline of threads, the code runs from top to bottom, the main thread is responsible for executing all of the program's Code (UI presentation and refresh, network requests, local storage, etc.) "a thread to do all things, think a little tired of it?"

    • Multithreading, as the name implies, is a program with multiple threads, which can be created by the user independently. Several processes that the user creates autonomously are child threads relative to the main thread. Both the sub-thread and the main thread are separate running units, and their execution does not affect each other, so it can execute concurrently.

Do you think it's a little dizzy to hear these dry theories? Coincidentally, I was dizzy at first glance. In the process of looking for information, I found a metaphor for someone else's image.

For example, a single thread is when you go to the kitchen and cook and cook, a person runs back and forth; Multithreading is two people, a single cook, a single cooking.

So, you better understand that?

And what is synchronous and asynchronous?

We use a simple example of life to illustrate.

You call the hotel and ask the staff if there is no room at this time, staff need to find out if there is room to answer you.

    • Syncing is not hanging up the phone until the staff tells you there is no room.

    • Asynchronous is hanging up the phone, you do other things, such as eating water, staff found the information and then call to tell you.

So our subject is here.

What is the asynchronous operation of JS?

JS's execution environment is single-threaded, that is, the program execution down, can only perform a task at a time, the program wants to run down, you must wait for the current task to complete, no matter how long the current task to execute (if the following program rushed out is really difficult to get it).

In order to solve the uncomfortable problem of the later procedure and so on. JavaScript has an asynchronous processing mode, in fact, delay processing.

Let's throw an example to illustrate.

  1.        var getUserInfo = function () {

  2.            $.getJSON("http://www.easy-mock.com/mock/5a09868228b23066479b8379/ajaxData/getUserInfo", function () {

  3.                return data;

  4.            });

  5.        }

  6.        var data = getUserInfo();

  7.        renderUserInfo(data)

GetUserInfo This function is called, to fetch the data in the background, it may take a lot of time, this will let Renderuserinfo wait until data is removed to run. Fortunately, JS has an asynchronous operation, when fetching data, do not have to wait for the renderuserinfo to be taken out, but directly execute.

So, what is the sequence of these two functions executing? No hurry, let's debug:

  1. var getUserInfo = function () {

  2.            console.log(‘aaa‘);

  3.            $.getJSON("http://www.easy-mock.com/mock/5a09868228b23066479b8379/ajaxData/getUserInfo", function () {

  4.                console.log(‘bbb‘);

  5.                return data;

  6.            });

  7.        }

  8.        var data = getUserInfo();

  9.        console.log(data);

  10.        console.log(‘ccc‘);

  11.        renderUserInfo(data);

The output of sequential execution thought it was "AAA", "BBB", "CCC"?

But things are not so simple. Let's take a look at the console output:

The results of the output are not sequential. In other words, when the function executes to the Getjson fetch data, the program does not wait for it to take out the data and then executes the next step, but skips the stage of fetching the data, executes the output database directly, and therefore, data is also empty.

This is the asynchronous mechanism of JS.

Self-Summary: The $.getjson method in this example can be brought into a callback function, after the callback function, you can execute a long process, while manipulating the contents of the callback function.

Asynchronous concept of "go" javascript

Related Article

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.