简体   繁体   English

回调和承诺如何在javascript中实现异步属性?

[英]How Callback and Promise Achieve Async Property in javascript?

I have a doubt the JavaScript Is a single-threaded synchronous programming Language.我怀疑 JavaScript 是一种单线程同步编程语言。 and it has only One Callstack .then How the Callback and promise Achieve Asycrones property?并且它只有一个 Callstack 。那么 Callback 和 promise 如何实现 Asycrones 属性?

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. Promise 确实会重新安排您的.then()回调,因为它就是这样设计的。 But all it does is execute the .then() at the end of your code.但它所做的只是在代码末尾执行.then() That's all it does, it does not execute the .then() callback in a separate thread.这就是它所做的一切,它不会在单独的线程中执行.then()回调。

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++.它们是使用 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).因此,如果一段 C/C++ 代码使用线程或信号或异步 I/O,它可以让 javascript 解释器使用 javascript 回调(它只接受稍后将调用的 javascript 函数)或承诺(它返回一个 javascript Promise 对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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