I am dynamically loading code (functions) from a server a开发者_如何学运维nd 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.
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.
Javascript is essentially single-threaded so you don't need a mutex. Your fetch could set up flags such that subsequent fetch calls could avoid making ajax calls e.g.:
var beingFetched = {};//map onflight -> callbacks
function fetch(foo){
if (foo in fooArray){
//Do Nothing
} else {
if (beingFetched.foo) { //note empty array is truthy
//register a callback
var callback = function(r){
//anything you need to do wit the return object r
//maybe even eval it.
};
//the callback would more likely be an argument to fetch itself
//or you could use a promise API instead so that you can at your will
//register multiple callbacks - for error, for success etc.
beingFetched.foo.push(callback);
} else {
beingFetched.foo = [];//truthy
//Fetch foo via Ajax and execute
$.ajax("getFoo/"+foo).done(function() {
_.each(beingFetched.foo, function(cb){
cb.apply(cb,arguments);
});
delete beingFetched.foo;
});
}
}
}
精彩评论