JQuery承诺迭代



我有一个数组,我需要遍历并发送一个Ajax调用。但是,我希望它串行发生(成功完成后的下一个(。我该如何有效地进行此操作?

$($('.logitem').get()).each(function(i,item) {
      $.ajax({
        type: "POST",
        url: 'http://localhost/save.php',
        data: {myData: $(item).html()}
      });
});

好吧,我不知道该解决方案的效率有多高,但是它确实可以从我的测试中起作用。

主要想法是使用发电机在您的项目列表上迭代。您可以使用.next()启动一次迭代器,还可以从AJAX请求的完整callback调用.next()

$(document).ready(function() {
    function request(item) {
        $.ajax({
            type: "POST",
            url: 'http://httpbin.org/post',
            data: { myData: $(item).html() },
            complete: function() {
                //Simulate delay in the call, remove the setTimeout in your code
                setTimeout(function() {
                    //Once this call completes, call the next one
                    console.log('Call completed for item : ' + $(item).text());
                    iterator.next();
                }, 1000);
            }
        });
    }
    function* ajaxGenerator(items) {
        for (let i = 0; i < items.length; i++) {
            yield request(items[i]);
        }
    }
    var logItems = $('.logitem').get();
    var iterator = ajaxGenerator(logItems);
    //Get things started
    iterator.next();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Test</title>
</head>
<body>
    <div class="logitem">Item1</div>
    <div class="logitem">Item2</div>
    <div class="logitem">Item3</div>
</body>
</html>

相关内容

最新更新