Promises in JS allow you to do async programming, as follows:
DoSomething().then(success, failure);
DoSomethingElse();
whenever i write th
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:
DoSomething
is called and it receives success
and failure
functions as arguments.
It does what it needs to do (probably initiating long-running AJAX call) and returns
DoSomethingElse()
is called
...
Some time later AJAX response arrives. It calls previously defined success
and failure
function
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.