2017-06-28 91 views
0

我有一个数组,我需要循环并发送一个ajax调用。不过,我希望它能够连续发生(在上一次成功完成之后进行下一步)。我如何有效地做到这一点?jQuery承诺迭代

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

只是为了确保,你想一旦前面的Ajax请求成功完成Ajax请求只发生? –

+0

正确.............. – KingKongFrog

+0

您定位的是什么Javascript版本? ES6好吗? –

回答

2

好吧,我不知道这个解决方案真的有多高效,但它似乎在我的测试中起作用。

主要想法是使用生成器遍历项目列表。您可以使用.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>