Promises 如何在没有线程的情况下在 Javascript 中实现 [英] How are Promises implemented in Javascript without threads

查看:18
本文介绍了Promises 如何在没有线程的情况下在 Javascript 中实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我看到 Promises 的概念在 AngularJS 和 JQuery 中实现.

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

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

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 ?

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);
                }
            }
        });
    }
}

推荐答案

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

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 中受益,并且不需要线程来实现它们.

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.

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

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

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 post for 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 中,promise 用于管理您的环境中已经存在的异步操作.它们不用于使非异步事物变为异步(您需要线程才能做到这一点).

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).

请记住,promise 本身只是监控工具,用于监控现有的异步操作.除了 .then() 之外,Promise 本身实际上并不是异步的,它可以使用内置 API 实现,例如 setTimeout()setImmediate()code> 或 nextTick().Promise 不需要它们自己的本机代码或线程.事实上,如果需要,您可以使用简单的单线程 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.

这篇关于Promises 如何在没有线程的情况下在 Javascript 中实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆