7

I'm trying to run one function after another function completes.

 $.when(saveCanvas(canvas)).done(setWallPaper());

Each function works fine on it's own but when I run the code above it only runs the first function.

What do I need to change?

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
  • 6
    Hard to answer without seeing the actual functions' implementations, but wild guess `$.when(saveCanvas(canvas)).done(setWallPaper);` – Fabrício Matté Mar 24 '13 at 02:41

3 Answers3

9

According to a comment on another SO question, $.when expects deferred objects as arguments. If you don't pass anything, the callbacks will be invoked immediately.

Does setWallPaper() appear to not be working because it is actually being run before saveCancas(canvas)? saveCanvas() is not actually a deferred object, which when expects it to be. To make it a deferred object, add dfr = $.Deferred(); to the beginning of your saveCanvas() function and return dfr.promise(); to the end of it. Check out this SO answer for more details.

function saveCanvas(canvas)
{
    dfr = $.Deferred();
    //Your code
    return dfr.promise();
}

Read more: http://api.jquery.com/jQuery.when/

Community
  • 1
  • 1
Luke Shaheen
  • 4,262
  • 12
  • 52
  • 82
2

Looking back at this now, this seems to be how it works with jQuery:

function f1() {
 alert("function one");
}

$.when( f1() ).done(function() {
  alert("function 1 is done running function two");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Note: This is identical to my method I posted in the question so essentially it should have worked. Though jQuery may have changed over the last 3 years. Most likely was a problem with functions being called.

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
1

another wild guess:

$.when(saveCanvas(canvas)).done(function(){
    setWallPaper()
});
Crash Override
  • 411
  • 6
  • 17