Are there any atomic javascript operations to deal with Ajax's asynchronous nature?

后端 未结 2 1778
再見小時候
再見小時候 2020-11-29 08:43

I am dynamically loading code (functions) from a server and executing it as javascript code then storing it in an array and executing. All these snippets of code must be ex

2条回答
  •  野性不改
    2020-11-29 09:09

    JavaScript is a nice language that works great with asynchronous callbacks, timeouts, intervals and user events, yet not having any concurrency problems. This is possible because JavaScript is essentially single-threaded - given piece of code is always executed atomically and never interrupted by another thread running JavaScript.

    Your fetch() function will always be executed without any interruption. If it is executed as part of the AJAX callback and if multiple AJAX callbacks are pending, they will be queued.

    Another example: if you have an event handler assigned to an input element and you fire the event multiple times at once, event handlers won't be executed concurrently. Instead they will be queued and executed sequentially. This also applies to multiple events triggered by setTimeout()/setInterval().

    As a side-note: this is one of the reasons why node.js is so robust: it uses only single thread and never blocks on I/O but uses callbacks instead when data is ready/event occurs.

提交回复
热议问题