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
.
If
a
returned a promise, then it will automagically pass the result on tob
when chaining together usingthen
Therefore what you want is
a().then(b)
.Note that
b
is not passed with parentheses, that would pass the result of callingb
to the chain. What you actually are doing is passing a reference tob
into the chain and say "Callb
when you have resolved the result ofa
".Here is a live example which demonstrates: http://jsfiddle.net/9wvb1d2a/