Why are javascript promises asynchronous when calling only synchronous functions?

前端 未结 2 714
攒了一身酷
攒了一身酷 2020-12-01 09:44

In testing I\'ve found that JavaScript Promises are always asynchronous regardless of whether or not they contain any asynchronous functions in their chain.

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 10:38

    Your code is fine is you want your promises to run independently and let them execute in their own way, no matter each one complete first. As soon as your code is async, you cannot predict which one will be completed first (due to the async nature of the event loop).

    However if you want to catch all your promises after they all completed, you should use Promise.all (which is the equivalent of $.when is jQuery). See:

    • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

提交回复
热议问题