有没有JavaScript的原子操作处理阿贾克斯的异步性质是什么? [英] Are there any atomic javascript operations to deal with Ajax's asynchronous nature?

查看:155
本文介绍了有没有JavaScript的原子操作处理阿贾克斯的异步性质是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是动态地从服务器上加载code(功能)并执行它的JavaScript code,那么它存储在一个阵列和执行。的code所有这些片断必须严格执行一次。该伪code如下这样

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');

所有四个将执行如果(FOO在fooArray),并认为它是不是数组中,所有的四会继续获取code和执行它。我记得早在一天学习旗语和互斥,是否有这样的事情对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是本质上的单线程 - 给一块code始终执行原子和另一个线程运行的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.

取()函数总是会没有任何中断执行。如果它被执行为所述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.

另外一个例子:如果你有一个分配给一个input元素的事件处理程序,你触发事件多次一次,事件处理程序不会被同时执行。相反,它们将被排队并顺序执行。这也适用于的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的原子操作处理阿贾克斯的异步性质是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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