Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...