Promises 如何在没有线程的情况下在 Javascript 中实现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25082867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:54:44  来源:igfitidea点击:

How are Promises implemented in Javascript without threads

javascriptjquerypromise

提问by Madhur Ahuja

Recently, I have been seeing the concept of Promises being implemented in AngularJS and JQuery.

最近,我一直在 AngularJS 和 JQuery 中看到 Promises 的概念。

I have seen the implementation of a Futures in Java as in code below, however this requires concept of thread pools to be present in language/platform. However, there is no such threading concept in Javascript. How are Promises in Javascript implemented then ?

我已经在 J​​ava 中看到了 Futures 在下面的代码中的实现,但是这需要在语言/平台中存在线程池的概念。但是,Javascript 中没有这样的线程概念。那么 Javascript 中的 Promises 是如何实现的?

public class Futures1 {

    private static final ExecutorService pool = Executors
            .newFixedThreadPool(10);

    public static void main(String[] args) {

        Future<String> contentsFuture = null;
        try {
            contentsFuture = startDownloading(new URL("http://www.example.com"));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        // other computation
        try {
            final String contents = contentsFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

    }

    public static Future<String> startDownloading(final URL url) {
        return pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                try (InputStream input = url.openStream()) {
                    return IOUtils.toString(input, StandardCharsets.UTF_8);
                }
            }
        });
    }
}

回答by jfriend00

Promises were invented to help manage asynchronous operations. Promises themselves do not need threads in order to do that. They are objects that essentially provide bookkeeping for asynchronous operations - keeping state flags, result values and listeners for a state transition. These are all things that can easily be done with regular single threaded Javascript.

Promise 的发明是为了帮助管理异步操作。Promise 本身不需要线程来做到这一点。它们是本质上为异步操作提供簿记的对象 - 为状态转换保留状态标志、结果值和侦听器。这些都是可以使用常规单线程 Javascript 轻松完成的事情。

So, as long as you have asynchronous operations (however those operations are implemented), you can benefit from promises and don't need threads to implement them.

因此,只要您有异步操作(无论这些操作是如何实现的),您就可以从 Promise 中受益,并且不需要线程来实现它们。

What it looks like you are seeing in your Java code is code that helps run regular tasks in a separate thread (to give synchronous operations some asynchronous-type behavior). That is not what promises do. So, if you already have asynchronous operations in your environment, you would not need this type of code in order to use promises.

您在 Java 代码中看到的代码有助于在单独的线程中运行常规任务(为同步操作提供一些异步类型的行为)。这不是承诺的作用。因此,如果您的环境中已经有异步操作,那么您将不需要这种类型的代码来使用 Promise。

Examples of asynchronous things in Javascript are pretty much anything that you register an interest in and the actual event occurs some time in the future and other code can run before that event fires. In a browser's Javascript environment, this includes things like setTimeout(), keyboard events, mouse events, ajax completion callbacks, etc... These are all asynchronous events. You register an interest in them (by registering an event listener or passing a callback to some function). Internal to the Javascript implementation, there are likely threads that are making these asynchronous events work, but those threads do not need to be exposed to the programmer directly for the asynchronous functionality to be there. For example, see this postfor how Javascript manages to run ajax calls in the background while other Javascript things are running. All you need to know is that your callback function will be called some indeterminate time in the future.

Javascript 中的异步事物的示例几乎是您注册感兴趣的任何事物,并且实际事件在将来的某个时间发生,并且其他代码可以在该事件触发之前运行。在浏览器的 Javascript 环境中,这包括诸如setTimeout()、键盘事件、鼠标事件、ajax 完成回调等……这些都是异步事件。您注册对它们的兴趣(通过注册事件侦听器或将回调传递给某个函数)。在 Javascript 实现内部,可能存在使这些异步事件工作的线程,但这些线程不需要直接暴露给程序员以实现异步功能。例如,看这个帖子了解 Javascript 如何在其他 Javascript 事物正在运行时设法在后台运行 ajax 调用。您只需要知道您的回调函数将在未来某个不确定的时间被调用。

So, in Javascript, promises are used to manage the asynchronous operations that are already present in your environment. They are not used to make non-async things become async (you would need threads in order to do that).

因此,在 Javascript 中,promise 用于管理您的环境中已经存在的异步操作。它们不用于使非异步事物变为异步(您需要线程才能做到这一点)。

Keep in mind that promises themselves are just monitoring tools, used to monitor existing asynchronous operations. Promises are not actually asynchronous themselves except for .then()which can be implemented with a built-in API such as setTimeout()or setImmediate()or nextTick(). Promises do not need their own native code or threads. In fact, you can write a promise implementation in plain, single threaded Javascript if you want.

请记住,promise 本身只是监控工具,用于监控现有的异步操作。Promise 本身实际上并不是异步的,除非.then()可以使用内置 API 实现,例如setTimeout()orsetImmediate()nextTick()。Promise 不需要它们自己的本机代码或线程。事实上,如果你愿意,你可以用简单的单线程 Javascript 编写一个 promise 实现。

回答by Katana314

The browser-written native code underneath the JavaScript layer tends to have threads implemented very neatly. As it turns out, that's usually all you need. Promises tend not to be needed for performing actual computation work in JavaScript (although workers make that easier) but for loading outside resources, and getting callbacks when they're done. JS Promises just assign callbacks to those functions like "image.onLoad" and check whether to notify another function.

JavaScript 层下的浏览器编写的本机代码倾向于非常巧妙地实现线程。事实证明,这通常就是您所需要的。在 JavaScript 中执行实际计算工作时往往不需要 Promise(尽管工作人员使这更容易),但用于加载外部资源,并在完成后获得回调。JS Promises 只是将回调分配给像“image.onLoad”这样的函数,并检查是否通知另一个函数。

Hogan may have summarized it best - event-based programming.

Hogan 可能总结得最好——基于事件的编程。