how is async programming (promises) implemented in javascript? isn't javascript a ui-threaded environment?

后端 未结 2 1311
后悔当初
后悔当初 2021-01-19 23:54

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

DoSomething().then(success, failure);

DoSomethingElse();

whenever i write th

相关标签:
2条回答
  • 2021-01-20 00:00

    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)

    • JavaScript equivalent of SwingUtilities.invokeLater()
    • Are there any atomic javascript operations to deal with Ajax's asynchronous nature?
    • jqGrid custom edit rule function using Ajax displays "Custom Function should return array!"
    0 讨论(0)
  • 2021-01-20 00:16

    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.

    0 讨论(0)
提交回复
热议问题