And when the real
def2
is ready, I can somehow link the real deferred to the mock one, i.e. make the real one synchronize its state with mock one.
This is actually what .then
does: It returns a new promise which gets resolved/rejected when the promise returned from the passed callback is resolved/rejected.
In order to make this work with $.when
, you have to keep a reference to the original promise:
function doOperation() {
var def1 = doSomeAsyncOperation();
var def2 = def1.then(function () {
return doAnotherAsyncOperation();
});
return $.when(def1, def2);
}
def2
will be resolved when the promise returned by the callback is resolved, i.e. the one that doAnotherAsyncOperation
returns.
But I don't think using $.when
is a good choice here, from a conceptional point of view. You are actually executing two asynchronous functions sequentially, but $.when
is used to run asynchronous functions in parallel.
I would just chain the function calls via .then
and collect the responses:
function doOperation() {
return doSomeAsyncOperation().then(function (resp1) {
return doAnotherAsyncOperation().then(function(resp2) {
return [resp1, resp2];
});
});
}
I'd say it's clearer here that doAnotherAsyncOperation
is executed after doSomeAsyncOperation
and the result of both calls is available to the caller of doOperation
.
You might have to do something similar for the fail case.