2

I'm learning asynchronous programming of javascript recently, it seems javascript does not have 'thread-api' like java.
In android, We can put slow functions into worker thread to avoid blocking ui operation.
So, how to implement the java function below via javascript:

public void execAsync() {
        new Thread(){
            slowFunction();
        }.start();
}
1

3 Answers 3

2

What you can thread in java in javascript it may be a 'web worker'.(i will give you and example with object+arrays not just a simple string)

let thread = new Worker("worker.js");

They communicate with messages

 thread.postMessage([first.value,second.value]);
 console.log('Message posted to worker');

at worker.js

onmessage = function(e) {
  console.log('Message received from main script');
  var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
  console.log('Posting message back to main script');
  postMessage(workerResult);
}
Sign up to request clarification or add additional context in comments.

1 Comment

firstly, in your worker.js (also) you'd need to have a postMessage call to send the data back to the file where you created the worker thread [new Worker("worker.js");]. Secondly, you need to add an onmessage event handler in the file where you initiated your worker thread. The communication b/w the main thread & the web worker thread is two way.
1

JavaScript and Java have totally different approaches to asynchrony. While Java has thread based concurrency, were the same code can run across different threads and works on the same memory, JS has task based concurrency with different agents that can exchange messages with each other.

Therefore you cannot just translate a thread based coding style into a task based one.

    Task based concurrency:                       Thread based concurrency:

 - time ->           ---- time -->           - time ->   - time ->   - time ->
 +-------+        +-------+ +-------+      +----------+  +----------+ +-----------+
 | Task  |        | task  | | task  |      | Thread   |  | Thread   | | Thread    |
 +-------+        +-----------------+      +--------------------------------------+
 | Agent |<-Msg ->| Agent           |      | Engine                               |
 | -Code |        | -Code           |      | -Code                                |
 | -Mem  |        | -Mem            |      | -Mem                                 |
 +----------------------------------+      +--------------------------------------+
 | Engine                           |
 +----------------------------------+

In most cases, one agent is enough in JavaScript, as you can offload most tasks (timers, IO) onto the engine:

 setTimeout(function() { // Task 1: Register the timer
  // Task 2: Do stuff when the timer triggers
  console.log("test");
 }, 1000);

The only case were you would really need more than one agent, is if you have work that you cannot offload, so in other words: Heavy computations. In those cases you can use multiple agents (WorkerThreads / ServiceWorkers in browsers, processes in NodeJS). These agents, unlike Java threads, don't share code and memory (except for SABs).

To get another WebWorker running in the browser, you have to start one specifying another file to run:

 const worker = new WebWorker("worker.js");

Then you can send/receive messages between the agents.

Comments

0

JavaScript is indeed single-threaded. https://developer.mozilla.org/en-US/docs/Web/javascript

You can work with service workers to get threads, see more here: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.