是否有任何原子 javascript 操作来处理 Ajax 的异步性质? [英] Are there any atomic javascript operations to deal with Ajax's asynchronous nature?

查看:33
本文介绍了是否有任何原子 javascript 操作来处理 Ajax 的异步性质?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从服务器动态加载代码(函数)并将其作为 javascript 代码执行,然后将其存储在数组中并执行.所有这些代码片段必须只执行一次.伪代码如下

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 executed exactly once. The psuedocode follows as such

function fetch(foo){
    if (foo in fooArray){
          //Do Nothing
    else{
          //Fetch foo via Ajax and execute foo()
    }
}

问题要复杂得多,但基本上如果我发出以下命令

The problem is vastly more complex, but essentially if I issue the below command

fetch('someFunctionName');
fetch('someFunctionName');
fetch('someFunctionName');
fetch('someFunctionName');

所有四个都将执行 if (foo in fooArray) 并假设它不在数组中,所有四个将继续获取代码并执行它.我记得那天学习信号量和互斥量时,javascript 有没有这样的东西.

all four will execute the if (foo in fooArray) and assume that it is not in the array, and all four will proceed to fetch the code and execute it. I remember back in the day learning about semaphores and mutexes, are there such things for javascript.

推荐答案

JavaScript 是一种很好的语言,可以很好地处理异步回调、超时、间隔和用户事件,但没有任何并发​​问题.这是可能的,因为 JavaScript 本质上是单线程的 - 给定的代码片段始终以原子方式执行,永远不会被另一个运行 JavaScript 的线程中断.

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.

您的 fetch() 函数将始终执行而不会中断.如果它作为 AJAX 回调的一部分执行,并且有多个 AJAX 回调未决,则它们将排队.

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.

另一个示例:如果您将事件处理程序分配给输入元素,并且您一次触发该事件多次,则事件处理程序将不会同时执行.相反,它们将排队并按顺序执行.这也适用于由 setTimeout()/setInterval() 触发的多个事件.

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().

附带说明:这就是 node.js 如此强大的原因之一:它只使用单线程并且从不阻塞在 I/O 上,但在数据准备好/事件发生时使用回调.

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.

这篇关于是否有任何原子 javascript 操作来处理 Ajax 的异步性质?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆