没有线程如何在Javascript中实现承诺 [英] How are Promises implemented in Javascript without threads

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

问题描述

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

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

我已经在Java中看到了Future的实现,如下面的代码所示,但是这要求在语言/平台中存在线程池的概念.但是,Javascript中没有这样的线程概念.然后如何实现Javascript中的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 ?

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

推荐答案

发明了帮助管理异步操作的承诺.承诺本身不需要线程就可以做到这一点.它们实际上是为异步操作提供簿记的对象-保留状态标志,结果值和状态转移的侦听器.这些都是使用常规单线程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实现内部,可能有使这些异步事件起作用的线程,但是不必为那些异步功能而直接将这些线程暴露给程序员.例如,请参见这篇文章有关在其他Java脚本运行时Java如何在后台运行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).

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

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

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