1

I'm hoping someone can help me better understand the need for the Promise feature in JavaScript. To me, they really just seem like asynchronous if-else statements. Having most of my experience in C++, I don't understand what a promise could do that couldn't be done with simpler syntax using an if-else statement running on separate threads.

I'm not trying to criticize the language, and I'm not doubting that there is a good reason for this feature, but I haven't managed to grasp it so far. Having used them in exercises, the code would be much more intuitive to me if I were able to set functions running on separate threads, merge them, and running an if-else statement on their outputs. Why was this language feature added in stead of just giving me control over splitting and merging threads?

Any help would be greatly appreciated. Thanks.

  • 1
    javascript is a single threaded environment – kevinSpaceyIsKeyserSöze Jan 22 '22 at 14:32
  • Multiple threads don't exist natively, outside of extensions like web workers and subprocesses. There is only one statement/expression that can be "running" at any given time (with others possibly on the stack and suspended) – CertainPerformance Jan 22 '22 at 14:35
  • 3
    I don't know C++, but C++ has promises (correct me if wrong), called "futures". So doesn't the question reduce to "why futures in C++?". Threads and promises are just different approaches to concurrency. With a single-threaded, event-driven async engine like JS, one doesn't have to use locks for "shared" variables, yet you have the benefits of not blocking on I/O that async offers. – ggorlen Jan 22 '22 at 14:38
  • 3
    Getting multiple threads or asynchronous tasks together and make it work without running into pitfalls or messy code is not easy. So many languages introduce the concept behind promises or techniques similar to them. C++ did that with the introduction of `std::async` and `std::future` and continued that path with coroutines that introduce something similar to `await`/`async`. – t.niese Jan 22 '22 at 14:39
  • `Why was this language feature added in stead of just giving me control over splitting and merging threads?` because JavaScript single threaded and event driven and not multi-threaded. You can only get subprocesses (Webworkers, workerthreads, child processes) but not “real” multithreading. – t.niese Jan 22 '22 at 15:03
  • Why do people keep believing JavaScript is single threaded? Where does this myth propagate from? – Benjamin Gruenbaum Jan 22 '22 at 16:57

0 Answers0