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?
CodePudding user response:
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).