jQuery function sync call

1.2k views Asked by At

How could I call a function, then when it's done, call another function passing the first function's return value as parameter? I read a lot about Deferred but can't figure out how it works.

https://api.jquery.com/category/deferred-object/

https://api.jquery.com/jQuery.Deferred/ and so on mainly on SO..

Here's some sample:

function a() {
   new amodel.AModel().save(vm.elem).done(function(_elem) {
      vm.elem(_elem);      
   }).fail(function(error) {
      ...
});

function b(param) {
  ... 
} //should call this with the a() return value

I tried to make it work as the follow:

$.when(a()).then(b());

This way I can't pass a parameter on, and I'm not even sure if it does what I would like to.

UPDATE:

Sorry, I wrote it wrong. I don't have to pass the return value as parameter, since when function a runs and gets done, it sets the value (vm.elem(_elem)) which will be used for an ajax call's parameter in function b.

1

There are 1 answers

4
Jamiec On BEST ANSWER

If a returned a promise, then it will automagically pass the result on to b when chaining together using then

Therefore what you want is a().then(b).

Note that b is not passed with parentheses, that would pass the result of calling b to the chain. What you actually are doing is passing a reference to b into the chain and say "Call b when you have resolved the result of a".

Here is a live example which demonstrates: http://jsfiddle.net/9wvb1d2a/