Reputation: 3166
I am new to jquery $.Deferred
and it seems that I cannot understand a whole bunch of stuffs regarding async processing.
Let say I wanna loop through usernames and login them, process something, and logout(this might not be necessary to include in the this question).
If I have this 2 user/pass combinations, I want to loop through them, login them and do necessary actions.
[{"username":"user1","password":"HardToKnow"},
{"username":"user2","password":"HardToKnow"}]
And I have created this function based on what I read, although I am not certain on how this works.
function login(user, pass) {
var d = $.Deferred();
$.post(
'http://www.domain.com/login',
{
user: user,
passwrd: pass
}
).done(function(s){
d.resolve(s);
}).fail(d.reject);
return d.promise();
}
The above function is obviously for login, and now I will have another function that must have another async request.
function setTodo(user,pass) {
return login(user,pass)
.pipe(function(s){
if (s.indexOf('<li class="greeting">Hello <span>' + user + '</span></li>')) {
return $.post().....?
}
return set(usr, pw);
});
}
That function above, although not complete, that i just my idea, will try to Set a todo and later another function will be called to submit or to finalize the todo
function submit(user, pass) {
return setTodo(user, pass)
.pipe(function(s){
// another $.post() here...
}
}
Question, am I doing it correctly? the deferred? How do I loop through the login credentials? I tried using $.each and ajax request them, but as expected they executed at the same time because it is async.
Upvotes: 0
Views: 953
Reputation: 4381
Yes. Overall you are doing it right, but note that pipe
is being deprecated in favor of then
.
Here is the documentation of then
.
Upvotes: 1