When are all my functions complete? - javascript

I have a set of async functions that issue executeSql commands to drop 2 tables, and have callbacks to create the 2 tables and populate the 2 tables.
I'd like to know when they have ALL completed.
I wouldn't mind if they executed synchronously. In fact, I'd prefer that they ran synchronously!
Q: Would I use the jQuery pipe method to queue up these functions so that they execute in a more traditional way than issuing callbacks?
I want to do something like:
DropTableA();
CreateTableA();
PopulateTableA();
DropTableB();
CreateTableB();
PopulateTableB();
window.location.replace('Index.htm');

Have a look at jQuery's Deferreds and Promises.
In short, here's an example of an async function that executes something asynchronously (setTimeout in this case). When calling the function you get back a promise.
var myFunc = function (value) {
var d = $.Deferred();
setTimeout(function () {
d.resolve(42 * value);
}, 1000);
return d.promise();
};
var promise = myFunc(100);
promise.done(function (res) { console.log(res); });
You can use $.when to execute something when all promieses have been fulfilled, i.e.
$.when(p1, p2, p3).then(...)
If you want to execute them in order you can chain the deferreds using the deffered's pipe.

If they are all sinchronous function (no async call inside those function) you are assured that window.location.replace('Index.htm'); is called after all of them. If you make ajax call you could do
jQuery.ajaxSetup( {async: false});
befare calling the first function and you are ok because all your AJAX call are now synchronous
http://jsfiddle.net/ywL63/

This is where jQuery deferred/promise come into play. Basically you modify your functions like this
function myAction1() {
var dfd = $.Deferred();
$(selector).whatever(function() { dfd.resolve(); // this is one of the callbacks});
return dfd.promise();
}
Then you can go and "wait" for all of the actions to complete with a construct like
$.when(myAction1(), myAction2(), ...).then(function() {
// this will be executed when all the actions finished = resolved
}

If your functions are synchronous, just call them in the right order, as you did in your example.
Assuming instead that your function returns a promise() or an observable object you can simply do
$.when(fn1(), fn2(), ... ).done(function() {
/* here you know that all functions have been returned, as you asked */
})
(note that you can use deferred objects not only for asynchronous tasks)
Edit: if order matters you can use this plugin:
jQuery.whenSync() Plugin For Chaining Asynchronous Callbacks Using Deferred Objects

Related

Creating jQuery Deferred objects using setTimeout

I am having a hard time understanding the value of creating your own Deferred object.
Say you have the following jQuery
function doStuffFirst() {
var dfd = $.Deferred();
// do some stuff here
setTimeout(function() {
dfd.resolve();
},1);
return dfd.promise();
}
function doStuffAfter() {
//do some other stuff
}
$.when(doStuffFirst()).done(doStuffAfter);
I don't actually know that doStuffFirst() has finished, its just waiting some time before firing doStuffAfter()
why is that any better than just going
function doStuffFirst() {
// do some stuff here
}
setTimeout(function() {
//do some other stuff
},1);
You do know that it is finished; but it is useless as it stands, since you're not executing your task asynchronously. The task executes, then the deferred gets created and fired almost immediately. However, if you change to this:
function doStuffFirst() {
var dfd = $.Deferred();
setTimeout(function() {
// do some stuff HERE
dfd.resolve();
},1);
return dfd.promise();
}
then it becomes useful, since it will return immediately, but resolve some time later (whenever the task is done). While you have just one async task, using a deferred is not much different than using a plain callback (just more complex, and prettier, and the dependency goes the other way: callbacks go in, while promises come out of the routine that schedules the task). However, if you have more complex requirements, like having two async tasks which you want to execute simultaneously but wait until both are done, promises are much superior.
Using setTimeout simply executes the code after the given time, whereas promises executes code once the promised task has completed. Promises are used when dealing with things in which completion time is unknown, such as ajax requests. In setTimeout, you know when exactly to execute some code.

AJAX asynch callback working correctly but how do I wait for the returned values

My main EXTJS function is calling three different AJAX asynch functions.The good news is that each AJAX function is successfully returning a boolean callback on whether the AJAX GET call was successful or not.
The problem - I need to perform additional post business logic from my main calling function once the boolean results have been returned from all three AJAX functions.
But as it is async the code will not wait for the async functions to complete and will fly through.
Any ideas on how I can get my code to GRACEFULLY wait until the typeof status is no longer 'undefined' ?
I am not near my code right now but here is a rough approximation.
function main(){
var status1, status2, status3, result1, result2,result3;
thisIsAsynchFunction1(args,function(result1){
status1 = result1;
});
thisIsAsynchFunction2(args,function(result1){
status2 = result1;
});
thisIsAsynchFunction1(args,function(result1){
status3 = result1;
});
// Perform logic based on callback from functions above
}
Thank You.
You cannot make Javascript wait. It simply doesn't work that way. What you can do is to trigger your final action when you discover that all three async results are done. Without redesigning your code to use promises (which would be the modern way to do this), you could do something like this:
function main(callbackFn){
var status1, status2, status3, doneCnt = 0;
thisIsAsynchFunction1(args,function(result1){
status1 = result1;
++doneCnt;
checkDone();
});
thisIsAsynchFunction2(args,function(result1){
status2 = result1;
++doneCnt;
checkDone();
});
thisIsAsynchFunction1(args,function(result1){
status3 = result1;
++doneCnt;
checkDone();
});
// Perform logic based on callback from functions above
function checkDone() {
// if all three results are done, then call the callback
if (doneCnt === 3) {
callbackFn(status1, status2, status3);
}
}
}
// call main and pass it a callback function
main(function(s1, s2, s3) {
// all three async results are available here
});
// Be careful because code here will execute BEFORE the async results are done
// any code that must wait for the async results must be in the above callback
A newer type of approach would be to have each async operation return a promise and when each async operation completes it would resolve its promise with its result. Then, you could use a promise library function (often called .when() to trigger a callback when all three promises were done. Many modern day JS libraries already return promises from ajax calls (such as jQuery) so the promise is already there.
I don't know ExtJS myself, but looked in its documentation and didn't see promise support yet and I found one thread discussing the fact that promises were not going to be in version 5. So, perhaps you just go with the counter design above or maybe ExtJS has some of its own support for monitoring when multiple async operations are all done.

jQuery's when.apply and wrapped async functions

I have code that requires waiting on a variable number of server responses along with loading several javascript modules via requireJS.
I want to leverage jQuery's when.apply. Unfortunately, the .then() portion of my code is always executing before ANY of my callbacks do.
Here is a summary of my code:
// load module func
function loadRequireJsModule(arg, callback) {
require([arg], callback);
}
// get layer info from server func
function getLayerInfoFromServer(arg, callback) {
var layerInfoListener = new DataLayer([arg]);
layerInfoListener.addRetrievedCallback(callback);
layerInfoListener.retrieveLayerInfo();
}
tasks.push( $.Deferred( function() {
loadRequireJsModule( "./" + layerJSON.type, function( module ) {
layer.controller = module;
});
}));
for (i=0; i<layerJSON.views.length; i++) {
layer.views[i] = {};
// get renderer class from require.js
tasks.push( $.Deferred( function() {
loadRequireJsModule( "./impl/" + layerJSON.views[i].renderer, function( index ){
return function( module ) {
layer.views[index].renderer = new module();
}
}(i));
}));
// POST request for layerInfo
tasks.push( $.Deferred( function() {
getLayerInfoFromServer( {
request: "configure",
layer: layerJSON.layer,
configuration: layerJSON.views[i]
}, function( index ){
return function( dataLayer, layerInfo ) {
layer.views[index].dataService = new TileService( layerInfo );
}
}(i));
}));
}
$.when.apply($, tasks).then( function() {
...
}
I'm worried that because my async functions are wrapped, jQuery is simply waiting until those functions end, which is immediate. I cannot pass jquery the naked async functions, they have to be wrapped. What do I have to do in order for my functions to be considered 'deferred objects'?
Edit - now that you've disclosed the actual code:
You are not using $.Deferred() correctly.
A typical usage in your context would look like this:
var d;
var tasks = [];
for (var i = 0; i < len; i++) {
// create new deferred object
d = $.Deferred();
// put deferred into tasks object
tasks.push(d);
loadRequireJsModule( "./impl/" + layerJSON.views[i].renderer, function( index, deferred ){
return function( module ) {
layer.views[index].renderer = new module();
// now that this operation is done, resolve our deferred
deferred.resolve();
}
}(i, d));
}
$.when.apply($, tasks).done(function() {
// code executes here when all the deferreds
// have had `.resolve()` called on them
});
Then, when all deferred objects that were put into the tasks array get resolved (by you calling .resolve()), then $.when() will fire.
You do not generally pass a callback to $.Deferred() like you were doing (that's used for something else and only used in special circumstances where you want to modify the deferred object in certain ways).
You MUST resolve or reject each deferred yourself by calling one of the methods on the deferred object that resolves or rejects it (there are four different methods that can be used).
Also, note that this structure runs ALL the async tasks in parallel (e.g. it fires them all at the beginning and then notifies you at the end when all of them have finished). You would need a different structure if you want them to run sequentially where you don't start the second one until the first has finished and so on.
If you want async behavior, then $.when() expects its arguments to be jQuery deferred or promise objects. So, for the structure of your code to work, the return from myAsyncWrapper() must be a jQuery deferred or promise object. That way, $.when() can monitor the promise objects for completion and when they are all complete, call your .then() handler.
Then, your async operations must either resolve or reject every one of the deferred objects that you passed to $.when() because it will only call its own .done() when ALL the deferred objects you passed to it have been resolved. Or, it will call its own .fail() if any of the deferred objects you passed to it is rejected.
If you are sure all the arguments you are passing to $.when() are deferreds or promises and your .then() handler is still getting called immediately, then your deferreds must already be resolved somehow because that's the likely explanation for why your .then() handler is called immediately.
If none of the arguments passed to $.when() are deferred or promise objects, then it will resolve itself immediately and thus call your .then() handler immediately which sounds like the behavior you are experiencing.
If your async operations are ajax calls, then jQuery.ajax() already returns a promise object that will be resolved when the ajax call completes. You can directly add the return result from jQuery.ajax() to your tasks array and pass that to $.when() and it will support your asynchronous behavior.
Using jQuery.ajax(), here's the concept for using $.when() with multiple concurrent ajax calls:
var promises = [];
for (var i = 0; i < myNum; i++) {
promises.push($.ajax(...));
}
$.when.apply($, promises).done(function() {
// put code here that runs when all the ajax calls have completed
// the results of all the ajax calls are in
// arguments[0], arguments[1], etc...
}).notify(function() {
// .notify is purely optional and only necessary if you want to be notified as
// each async operation completes
// This will get called as each async operation completes with whatever arguments
// were passed to the success handler
}).fail(function() {
// this will get called immediately if any of the async operations failed
// the arguments are the same as the .done() function except that some may be empty
// if they didn't complete before one of them failed
});
Obviously, you don't have to use all three operations .done(), .notify() and .fail() or you can specify all of them in .then() - I just included all three with comments for educational purposes.
If you want help with some other type of async operation that doesn't already create its own promise object, then I'd be happy to help if you show and describe the actual operation. Deferreds are confusing to get a handle on initially, but like many things are actually quite simple and extremely useful once it finally sinks in.
There is an alternative I found for processing a loop of parallel promises without using an array. Instead use the pattern promise = $.when(promise, anotherPromise).
e.g. for you example something like this
// Start with an empty resolved promise - undefined does the same thing!
var promise;
for (i = 0; i < layerJSON.views.length; i++) {
layer.views[i] = {};
// get renderer class from require.js
promise = $.when(promise, loadRequireJsModule("./impl/" + layerJSON.views[i].renderer, function (index) {
return function (module) {
layer.views[index].renderer = new module();
}
}
));
}
// Now do something after all the promises are resolved
promise.then(function () {
// Do the next part
});
This example assumes you change getLayerInfoFromServer to return a promise:
Notes:
The downside of this technique is that the return values of the individual promises are nested within each other, in reverse order, so are not very useful. It is great if you just need to know when it has completed all tasks.

JavaScript pattern providing optional callback interface but use promise inside

I want to create a function, let's say a readConfig function.
readConfig(path [, callback(err, config)])
The callback here is optional. If there is no callback when called, the function will only use synchronous methods (readFile(path) and configParser(string) which return promises) to read the file and directly return the parsed config object. Exceptions are thrown directly. However when callback is provided, the function will use asynchronous methods and call the callback after finished. Exceptions are directly raised to callback but not thrown.
There are many similar codes to do sync and async work, so I want to use one method for both. How can a promise like function detect an async or sync call according to the caller's callback argument? And how can we ensure that the promise will act in synchronous way? Please show me a pattern for that.
I can't speak to the promise acting in a synchronous way, but in JavaScript you can do arguments.length to get the number of arguments passed to a function. If that equals 2 and typeof arguments[1] === 'function', then you have a second argument that is a function.
As for personal taste, I'd recommend just having 2 different functions, one of them ending in Sync, à la http://nodejs.org/api/fs.html. This module is replete with function pairs where one is async and the other isn't.
Also, remember that this is not async code:
function notAsync(cb) {
cb(null)
}
That callback executes in the same tick. You need to wrap it like so:
function async(cb) {
process.nextTick(function(){ cb(null)})
}
or something like that.
Whatever you decide, happy coding.
In this example, I'm using jQuery's deferred api. I wrap the callback in .when which allows you to attach a .then() to the callback, whether it is synchronous or asynchronous with a promise.
The solution should be to use your promise api's when. http://howtonode.org/promises
Live demo (click).
$('#sync').click(function() {
foo(function() {
});
});
$('#async').click(function() {
foo(function() {
var deferred = new $.Deferred();
setTimeout(function() {
deferred.resolve();
}, 500);
return deferred.promise();
});
});
function foo(callback) {
$.when(callback()).then(function() {
console.log('done!');
});
}

Late binding for jQuery.when

I am working with a framework that uses jQuery Deferred Objects.
In my code, one async operation should executed successfully so that another async operation be executed.
function doOperation() {
var def2mock = $.Deferred();
var def1 = doSomeAsyncOperation().done(function () {
var def2 = doAnotherAsyncOperation();
});
return $.when(def1, def2mock);
}
So I put the call for the second operation in the "done" promise of the deferred of the first operation as in the example.
Now, I wrap this sequence with the function doOperation. The result of doOperation should be the join of the two deferreds of both async calls. Meaning doOperation succeeds if all async operations succeed and fails if any of them fail, which is exactly what $.when does.
The problem is that in order to create the join with $.when, I need both deferreds present at the time $.when is called. And because the deferred of the second async operation is not available at that moment, I had to find a way to create the join first, then add the deferred of the second async operation to the join later.
To do this, I thought I can define a new mock $.Deferred named def2 in doOperation. And when the real def2 is ready, I can somehow link the real deferred to the mock one, i.e. make the real one synchronize its state with mock one. The only way I found was to do
def2.done(def2mock.resolve)
// and
def2.fail(def2mock.reject)
but I don't feel this manual linking is the right way to do it.
So please tell me if you have a better suggestion on how to do it the right way.
And when the real def2 is ready, I can somehow link the real deferred to the mock one, i.e. make the real one synchronize its state with mock one.
This is actually what .then does: It returns a new promise which gets resolved/rejected when the promise returned from the passed callback is resolved/rejected.
In order to make this work with $.when, you have to keep a reference to the original promise:
function doOperation() {
var def1 = doSomeAsyncOperation();
var def2 = def1.then(function () {
return doAnotherAsyncOperation();
});
return $.when(def1, def2);
}
DEMO
def2 will be resolved when the promise returned by the callback is resolved, i.e. the one that doAnotherAsyncOperation returns.
But I don't think using $.when is a good choice here, from a conceptional point of view. You are actually executing two asynchronous functions sequentially, but $.when is used to run asynchronous functions in parallel.
I would just chain the function calls via .then and collect the responses:
function doOperation() {
return doSomeAsyncOperation().then(function (resp1) {
return doAnotherAsyncOperation().then(function(resp2) {
return [resp1, resp2];
});
});
}
DEMO
I'd say it's clearer here that doAnotherAsyncOperation is executed after doSomeAsyncOperation and the result of both calls is available to the caller of doOperation.
You might have to do something similar for the fail case.
I don't have any experience with Deferred (nor do I fully understand what it does), but if you are just looking to chain operations, would something like this work?
function doOperation(operations) {
var wrapper = {};
wrapper.index = 0;
wrapper.operations = operations;
wrapper.onthen = $.proxy(function() {
if (this.index < this.operations.length) {
this.operations[this.index]().then(this.onthen);
}
this.index++;
}, wrapper);
wrapper.onthen();
}
Here's a demonstration: http://jsfiddle.net/vz6D7/2/

Categories