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

后端 未结 2 1312
后悔当初
后悔当初 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!"

提交回复
热议问题