I have a problem i´m trying to solve by using deferred objects in javascript (and i am new to deferred objects).
The problem: The user tries to run a function (can be alot of different functions). If the function fails...it will try to login again and then try again (one time). If login fails. Well then all fails.
These functions and the login function contains an Ajax call that will be returned.
My Question is: Can i rely on that var dfd (at the end of the tryAjax function) to be executed last after all other code in the function has run?
Here is the code:
function tryAjax(func)
{
var dfd = new jQuery.Deferred();
window[func]().then(
function(p1,p2,p3)
{
//Everything worked great. No need to login.
dfd.resolve(p1,p2,p3);
},
function()
{
//func failed
//try to login user again before trying.
loginUser().then(
function()
{
//Login success
//Try to run func again.
window[func]().then(
function(p1,p2,p3)
{
//Func succes after login
dfd.resolve(p1,p2,p3);
},
function(p1,p2,p3)
{
//Func failed after login
dfd.reject(p1,p2,p3);
});
},
function(p1,p2,p3)
{
//Login failed
dfd.reject(p1,p2,p3);
});
});
return dfd;
}
And to call it:
tryAjax('getData').then(
function(p1,p2,p3)
{
//Success
},
function(p1,p2,p3)
{
//Error
});