0

I am calling two functions in $.when(f1,f2) but done() is called before f2 is resolved. But if I put alert() statement in done It is working fine.

function f1(){
var d= new $.Deferred();
 .......code......
 d.resolve();
 return d.promise();
}
function f2(){
var d= new $.Deferred();
 .......code......
 d.resolve();
 return d.promise();
}
function f3()
{.....code.....    }

 $.when(f1().f2()).done(f3());

above code is calling f3 even before f2() is resolved. But if I put alert statement in done() It is working fine.

 $.when(f1().f2()).done( alert ("came here");f3());

this is executing in proper sequence.

same is with $.when(f1,f2).then() also. could anybody please tell me what could be the reason for this unusual behaviour.

N.Moudgil
  • 709
  • 5
  • 11

2 Answers2

1

.done() needs to be passed a function reference like this:

 $.when(f1(),f2()).done(f3);

You also need a comma (not a period) between your two arguments to $.when(), but I assume that's just a typo in your question.

When you did $.when(f1(),f2()).done(f3());, with the parens after f3, that executes f3() immediately and then passed it's return value to .done() which is not likely what you want.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
-1

proper syntax,

give the $.when() method promise's.in your code I can see dot instead of comma between two function calls in $.when() method.

proper syntax is

$.when(f1(), f2()).then()  

or

$.when(f1(), f2()).done()
Bharadwaj
  • 2,535
  • 1
  • 22
  • 35
sundar
  • 398
  • 2
  • 12
  • Thanks @sundar here while asking question I mistyped but in my code I am using "," only-- $.when(f1(),f2()).done(); – N.Moudgil Jan 15 '16 at 07:24
  • @N.Moudgil there is no possibility of happening like that.how do you say done() is calling before f2()? – sundar Jan 15 '16 at 07:27
  • from your code what i can see is you are resolving all promises(promise inside f1 and f2 method's) before the promise is returning from the f1() and f2().please add console.log in three methods f1, f2 and done.check the flow – sundar Jan 15 '16 at 07:32
  • if you want appropriate answer for your question pls post exact code you are using.we can only give you the correct answer if you post your code without any typo's.how can we know that's a typo or that's an actual bug that affects your code. – sundar Jan 15 '16 at 07:37
  • thnx @sundar..I am testing in iOS 8 iph 5s using phonegap and facing this issue. And while testing in android nexus 6(lollipop) I get different execution flow. – N.Moudgil Jan 15 '16 at 09:25
  • i dont understand what you are saying.behavior of jquery is same for all devices.pls correct your code.follow the docs.and add only callback methods in done and then method.dont directly do your logic there. – sundar Jan 15 '16 at 09:33