简体   繁体   中英

How Callback and Promise Achieve Async Property in javascript?

I have a doubt the JavaScript Is a single-threaded synchronous programming Language. and it has only One Callstack .then How the Callback and promise Achieve Asycrones property?

They don't. Callbacks and Promises do not make anything asynchronous. Instead callbacks and Promises are design patterns allowing asynchronous functions to interact with the rest of your code.

The following are two example of callbacks, one is synchronous, one is asynchronous:

function a (input, callback) {
    callback(input * 2);
}

function b (input, callback) {
    setTimeout(() => callback(input *2), 100);
}

console.log('start!');

a(100, x => console.log(x));
b(1000, x => console.log(x));

console.log('end!');

The output should be:

start!
200
end!
2000

Callbacks don't make anything asynchronous but is a technique of allowing asynchronous code to interact with other parts of your code.

Promises do re-schedule your .then() callback because that's the way it was designed. But all it does is execute the .then() at the end of your code. That's all it does, it does not execute the .then() callback in a separate thread.

How does it execute your code later? Well, your code is a function. It simply calls it later. How does it call it later? It simply adds your function to a list of things that needs to be done later. At the end of your code the interpreter will check this list (or lists) to see if it needs to do anything. This part of code that checks if anything needs to be executed is called the event loop. The things in the list/lists that needs to be checked are called "tasks" or "microtasks" in the documentation.

Asynchronous functions are asynchronous. They are implemented using C/C++. So if a piece of C/C++ code uses threads or signals or async I/O it can let the javascript interpreter wait for the asynchronous results using javascript callbacks (it simply accepts a javascript function that it will call later) or promises (it returns a javascript Promise object).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM