4

Promises in JS allow you to do async programming, as follows:

DoSomething().then(success, failure);

DoSomethingElse();

whenever i write the previous code it reaches DoSomethingElse() before it reaches success. How is that possible? Isn't JS a single threaded environment (not including web-workers)? is it done with setTimeout?

Elad Katz
  • 7,483
  • 5
  • 35
  • 66
  • 2
    The issue is addressed pretty well here: http://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded – Pekka Mar 18 '12 at 11:56
  • `async` does not imply `concurrent` that is where you are going wrong. –  Sep 05 '15 at 02:15

2 Answers2

5

Yes, JavaScript is single-threaded, which means you should never block this single thread. Any long-running, waiting operation (typically AJAX calls or sleeps/pauses) are implemented using callbacks.

Without looking at the implementation here is what happens:

  1. DoSomething is called and it receives success and failure functions as arguments.

  2. It does what it needs to do (probably initiating long-running AJAX call) and returns

  3. DoSomethingElse() is called

  4. ...

  5. Some time later AJAX response arrives. It calls previously defined success and failure function

See also (similar problems)

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • when doing an ajax call, the xhr object is the one that's opening a new thread, so that's not really the issue.. what if it's not an ajax call? what if the long task is sorting an array for example? how is that implemented? – Elad Katz Mar 18 '12 at 12:07
  • 3
    @EladKatz: it is not, when performing long-running CPU-intensive tasks (like sorting an array or huge DOM manipulations) the UI thread is occupied and the GUI is blocked (freezes). No timeouts are executed, no AJAX response handled, no click event handlers called. Sorry. – Tomasz Nurkiewicz Mar 18 '12 at 12:10
0

Promises in JavaScript usually involve some kind of call chains or fluent method call APIs, where function results usually provide continuation methods like with, then, when, whenAll etc plus some status flags that indicate if the result is in fact available. Functions with input parameters can also support promised values detecting that the input is a promise and encapsulation their functionality into a thunk that can be chained when the promised value is ready.

With these you can provide an environment where promises simulate a parallel language like this:

MyApi.LongRunningTask().then( function(result) { MyAppi.LongOtherTask(result); }).then

or a sequential use case where long running calls are not dependant:

var value1 = MyApi.LongRunningTask();
var value2 = MyApi.LongRunningOtherTask();

MyApi.DoSomeFunction( value1, value2).then ==> DoSomeFunction can check if values are ready and if not chains their then/when function to execute its logic.

Peter Aron Zentai
  • 11,482
  • 5
  • 41
  • 71