简体   繁体   English

使用deferred和promise循环ajax调用

[英]Looping ajax calls using deferred and promises

I am new to jquery $.Deferred and it seems that I cannot understand a whole bunch of stuffs regarding async processing. 我是jquery $.Deferred ,看来我听不懂关于异步处理的所有内容。

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. 如果我有这2个用户/密码组合,则想遍历它们,登录它们并执行必要的操作。

[{"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. 我尝试使用$ .each和ajax请求它们,但由于它们是异步的,因此按预期它们会同时执行。

Yes. 是。 Overall you are doing it right, but note that pipe is being deprecated in favor of then . 总之你正在做的是正确的,但要注意, pipe被弃用,取而代之的then

Here is the documentation of then . 这是then的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM