1

This is more of a project planning question.

If I were to receive an array of n objects from a REST API. Now I would need to process n requests at once. I understand JavaScript is a single threaded language. Would this be a problem?

const array = [{foo: 1}, {foo: 2}, {foo: 3}, {foo: 4}, {foo: 5}]

Would it be possible to then do element.foo + 1 on each instance at once?

1
  • This is rather vague, what do you mean by "process n requests at once"? Is there anything that prevents you from processing one element after the other, and if yes, what? Note that having multi thread languages don't extend the machine capabilities, performance is not really a criteria here. Commented Jul 2, 2020 at 11:35

1 Answer 1

2

It depends on what kind of processing you need to do:

  • If the processing is I/O, Node.js uses asynchronous non-blocking I/O so you can generally just process each request individually and they'll be handled in parallel because Node.js won't block the event loop while waiting for I/O to happen. (This is why you don't use the xyzSync API calls; they block.)

  • If it's a lot of CPU processing rather than I/O, you can use separate threads for it via workers.


I understand JavaScript is a single threaded language.

Until fairly recently, JavaScript the language was silent on the topic of threads, and fully concurrent multiple-threading implementations did and do exist (for instance, JavaScript support in the Java JDK).

More recently, though, the specification has added the concept of agents and the idea that an agent has a single executing thread so, in general, there's only one thread acting within a given global environment (only one thread changing shared variables, absent the use of SharedArrayBuffer). But there can be multiple agents in an environment, as there are on web browsers (different windows can have different threads, web workers have their own threads, etc.) and Node.js (worker threads), and they can even share memory via SharedArrayBuffer.

Sign up to request clarification or add additional context in comments.

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.