if i fire up 2 functions like this:
prepare_data();
read_data();
then i guess they are running at the same time. but as you can see function two is depending on the first one, so how can i make the latter one run after the first one is completed?
Javascript, and most other languages, run code sequentially.
Therefore, they will not both run at the same time.
In fact, it is not possible to run two different pieces of Javascript code at the same time. However, in many other languages, it is possible using threads.
However, if they make AJAX calls, the corresponding server-side code called by both functions will run simultaneously.
To prevent that, you'll need to make the first function accept a callback parameter and pass it the second function.
I'm assuming the first call makes some kind of asynchronous call that the second relies upon because otherwise the two functions will execute sequentially.
If so you need to do the second in the callback from the first. For example, in jQuery:
function prepare_data() {
$("#data").load("/load_data.php", function() {
read_data();
});
}
It's impossible to say how you should solve this without more information on whether you're using vanilla Javascript or a particular library. I'd strongly suggest using a library of some sort for AJAX however.
May be you want to call Second function after first function function to be successfully executed, if so, then you can do this by this
$('button').click(function()
{
function1(someVariable, function() {
function2(someOtherVariable);
});
});
function function1(param, callback) {
alert('Now first function will be called.');
callback();
}
#SLaks
In fact, it is not possible to run two
different pieces of Javascript code at
the same time. However, in many other
languages, it is possible using
threads.
Is this completely correct? cant you run javascript parallely using web workers ?
http://www.w3.org/TR/2009/WD-workers-20090423/
https://developer.mozilla.org/En/Using_web_workers
Related
I have a couple of user interfaces where different asynchronous processes can be running simultaneously. When some of them finish, they need to do things like refresh some or all of the UI. To avoid the need to run the refresh multiple times, I use a setTimeout function to run the refresh so it runs only once even if 'triggered' from multiple simultaneous processes. e.g.:
var runCleanupTimeout;
function runCleanupOnce() {
if (runCleanupTimeout) clearTimeout(runCleanupTimeout);
runCleanupTimeout = setTimeout(function () {
refreshUI();
}, 250);
}
I know I can pass a callback into this also as well as pass the actual timeout as a variable to the function, but I'm starting to work with using Promises in functions that finish at some later time and I'm wondering how to implement such a thing as an abstract promise.
Currently I'm using a single timer (thus the static values and function calls - I seldom need more than one of these in a single UI, but when I do, I create a second variable and a second function with a fixed timeout)
I'd like to be able to write a generic utility-function as a promise so any time I want to do a run-only-once, I just call something like:
utilities.runOnce('someTimerId',250).then(
function() {
refreshUI();
}
);
I know I could instead use an array/associative array where I specify the id for the 'timer' and use a custom callback type structure. But I'm not entirely sure how this would work in a promise.then() structure. I saw one example using a .bind property but can't find a good reference on what bind() is doing in that case.
Any help to figure this out is appreciated.
Promises turned out to not be a good solution as a run-once type process only has one discreet resolve
I have a function with 3 ajax calls
var loadEditModalAddressData(){
loadCountries();
loadStates();
loadDistricts();
};
I want from js to wait, until all ajax calls are finished.
Part of my code
loadEditModalAddressData();
$(document).ajaxStop(function(){
// functionality using requested data
....
}
This worked fine, until I added extra features and figured out that $(document).ajaxStop is called after every complete request(or bunch of requests),not only in certain function scope, which mash up my code functionality.
How do I do that?
The dirty way could be to use a counter in ajaxStop to make sure all three calls have returned. A slightly better way could be to add callbacks to each of your calls and to launch the treatment when the last is received.
However, the best way is probably to use promises.
If you use jQuery to do your calls, you can do stuff like:
$.when(call1, call2, call3).then(function(results){
// your stuffs
});
Where the callX are what returns $.get (or any other jQuery promise).
Have a look here.
Use $.when to wait for multiple defereds/promises. It's synonymous to the native Promise.all().
XCode has webkit built in, and XCode can issue a JavaScript command and receive a return value. All that is good - except when JavaScript has a callback function like with executeSql.
How do you write a function that doesn't return until the callback has been called?
Do you wrap it in another function maybe?
There are two solutions - you may either write your entire program in continuation passing style or you may use trampolines to simulates real continuations.
If you want to use continuation passing style then I suggest you first read the following StackOverflow thread: What's the difference between a continuation and a callback?
Continuation passing style can be a pain to write. Fortunately there are JavaScript preprocessors like jwacs (Javascript With Advanced Continuation Support) which ease writing such code: http://chumsley.org/jwacs/
The second option (using trampolining) currently only works in Firefox and Rhino. Sorry XCode. You can read more about trampolining here: Trampolines in Javascript and the Quest for Fewer Nested Callbacks
If it interests you then I've written a small fiber manager for JavaScript that allows you to call asynchronous functions synchronously: https://github.com/aaditmshah/fiber
May I suggest checking it periodically?
var executeSqlIsDone = false;
executeSql({
callback: someCallbackFunction();
});
waitUntilCallbackIsFinished();
//continue processing
function someCallbackFunction()
{
executeSqlIsDone = true;
}
function waitUntilCallbackIsFinished()
{
if(executeSqlIsDone === false)
{
setTimeout(waitUntilCallbackIsFinished, 100); //some low value
}
//else - do nothing. Wait.
}
Also look into
This might be the opposite of my previous question here but anyway, I need to know its answer as well.
I have an Ajax call in my algorithm that I need to wait for it to run some code. There are two solutions:
1) The typical solution:
ajaxCall(function(result){
//the code to run after the call is returned
});
2) The one I'm wondering if it can be an alternative:
res=null;
ajaxCall(function(result){
res=result;
});
while(res==null)/*wait! but this will lock the GUI I guess*/;
//do the rest of the code because now res is initialized
The question is how can I write the second solution in an efficient way that doesn't freeze the GUI?
Just make the ajax call synchronous.
ref: http://developer.mozilla.org/en/XMLHttpRequest
look for the async parameter
I suggest hooking all dependent code to execute as a callback from your ajax call 's return. That way, all other javascript can continue to execute and you will not make your browser unresponsive for the duration of the call.
Alternatively, which is not something I would never ever do, you can make your ajax call synchronous, using async: false like so:
$.ajax({ url: ..., async: false });
A generic answer:
There are only two methods available in async. programming: events and callbacks. Period.
(Technically speaking, there is not really a difference between the two on the lowest level, an "event" is just a (library) function - the one doing the event "firing" - executing all functions registered as listeners so it's the same as a callback - technically, i.e. when you write event.fire() or whatever the event syntax of your preferred lib it's synchronous invocation of all registered event handler functions). When to use one or the other is a matter of preference, convention and style when designing an API.)
Javascript programming, especially AJAX, is asynchronous by definition. So if you have an algorithm that needs to "wait" for something, you're better off reconsidering the algorithm. Ironically enough, Javascript syntax is not best suitable for async programming, but there are many libraries that help you keep callbacks under control and avoid spaghetti code.
Example of callbacks spaghetti:
function ajaxRequest(url1, function() {
animateSomething(div, function() {
ajaxRequest(url2, function() {
....
})
})
})
the same with async.js looks much cleaner:
async.series([
function(_) { ajaxRequest(url1, _) },
function(_) { animateSomething(div, _) },
function(_) { ajaxRequest(url2, _) }
])
there are many ways to do this one. one of the is passing a callback to the ajax (or at least a reference of it). your code #1 would be an example of that.
another is that you have a notifier object which you add the ajax success call to it. then you can have other functions (one or more) plug into it to listen for a "success" announcement.
Sorry about the title but could not come up with anything really informative and concise.
My situation is that I am launching a setTimeout and I want it to be able to run in the middle of a JS function (it is used to get around the issue with injecting GM functions into the web page).
unsafeWindow.testG = function(key, dValue){
var rValue;
setTimeout(function(){rValue = GM_getValue(key, dValue);}, 0);
alert(rValue);
alert(rValue);
return(rValue);
}
In the three tests rValue is still undefined (which makes sense because JS is single threaded for the most part).
So I have 2 solutions I have thought of.
Favourite:
Is there anyway to tell JS to sleep in the middle of a function and work on background stuff (like Timeouts)?
Other:
Does anyone know when this timeout will be called? Maybe after this function execution but before whatever called it starts up again?
In that case making rValue global would solve the issue (but make slightly messier coding).
Or will it wait until all JS is done executing?
In that case I would possibly need another setTimeout to process the result.
There is no way what you're asking for can be accompished. Until HTML5 is a wide spread standard, you can't do what you're asking without thinking asynchronously.
For example :
unsafeWindow.testG = function(key, dValue, callback){
var rValue;
setTimeout(function(){
rValue = GM_getValue(key, dValue);
callback(rValue);
}, 0);
}
and call this with a callback :
unsafewindow.testG(key, dValue, function(rValue) {
alert(rValue);
});
alert("foo");
For the last sippet, "foo" will be echoed before rValue, because testG will execute the timeout function only when the Javascript thread is available, or only when there's no other script running.
To answer your first question, there is no 'sleep' function in JS. In fact, there is a site devoted to trying to create one: http://www.devcheater.com/ The conclusion: you cannot.
If what you'd like to do is make the rest of your code run later, you can put that code in a function and setTimeout().
Of course, the usual way to handle the sort of scenario you have set up is with callbacks. Since you're basically waiting for the thing in setTimeout to happen, you can have it call the rest of your code whenever it's done. For example:
var fartResult
function waitAMinuteThenFart (callback) {
function fart () {
fartResult = 'fart'
callback(fartResult)
}
setTimeout(fart, 1000*60)
}
waitAMinuteThenFart(function (result) { alert(result) })