Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are Promises implemented in Javascript without threads

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

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);                 }             }         });     } } 
like image 380
Madhur Ahuja Avatar asked Aug 01 '14 14:08

Madhur Ahuja


People also ask

How do Promises work if JavaScript is single threaded?

Promises in JS are a way to do asynchronous programming, which is not the same as multithreading. Essentially, in synchronous single-threaded code, when there's some some sort of IO, the processor just issues an instruction to other hardware, and that's it.

Do Promises use threads?

Promises are a way to orchestrate asynchronous tasks without directly using threads and shared data.

Do Promises run on main thread?

As I mentioned before, JavaScript code is executed on a single thread. The callback that processes the response from your created Promises still runs on your single main thread. Promises do, however, allow you to spawn asynchronous tasks, such as file I/O or making an HTTP request which runs outside of your code.

How promise is implemented in JavaScript?

There are three main ways to consume a Promise: then() , catch() , finally() . . then(res => onFulfilled(res), err => onRejected(err)) — takes two functions defined by the consumer. They are called after a Promise is resolved or rejected.


1 Answers

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.

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.

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.

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.

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

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.

like image 129
jfriend00 Avatar answered Sep 20 '22 05:09

jfriend00