Question

How can I wait until the end of the two functions, and only after calling callbacks for them to continue the script.

I paid attention to jQuery deferred.then(), but I do not understand how to use it in my case

GoogleDriveModule.checkAuth(function(authResult) {
  if (authResult) {
    return parts_count += 1;
  }
});

DropboxModule.isAuthenticated(function(authResult) {
  if (authResult) {
     return parts_count += 1;
  }
});
Was it helpful?

Solution

Create two deferred objects and resolve them within the callbacks. Then you can wait on both deferreds with $.when:

var googleDone = $.Deferred(),
    dropboxDone = $.Deferred();

GoogleDriveModule.checkAuth(function(authResult) {
  googleDone.resolve();
  if (authResult) {
    return parts_count += 1;
  }
});

DropboxModule.isAuthenticated(function(authResult) {
  dropboxDone.resolve();
  if (authResult) {
     return parts_count += 1;
  }
});

$.when(googleDone, dropboxDone).then(function() {
    alert("Both authentication checks completed.");
});

OTHER TIPS

You could have 2 boolean and check in a callback function if they are ready :

var gDriveREADY = false, dBoxREADY = false;
GoogleDriveModule.checkAuth(function(authResult) {
    if (authResult) {
        return parts_count += 1;
    }
    gDriveREADY = true;
    doSomething()
});

DropboxModule.isAuthenticated(function(authResult) {
    if (authResult) {
        return parts_count += 1;
    }
    dBoxREADY = true;
    doSomething();
});

function doSomething(){
    if(dBoxREADY && gDriveREADY){
        //Your code
    }
}

In the callbacks you could toggle a simple flag which the other function checks:

var driveDone = 0
  , dropDone = 0
  ;
GoogleDriveModule.checkAuth(function(authResult) {
  driveDone = 1;
  if (authResult) {
    parts_count += 1;
  }
  if(dropDone){
   bothDone();
  }
});

DropboxModule.isAuthenticated(function(authResult) {
  dropDone = 1;
  if (authResult) {
     parts_count += 1;
  }
  if(driveDone){
   bothDone();
  }
});
function bothDone(){}

This has less overhead than the deferred method, but is not quite as clean.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top