如何在multile Jquery Get函数中等待

时间:2016-03-01 06:54:19

标签: javascript jquery html json get

在下面的代码中,我遍历每个域并通过jQuery GET函数执行一些操作。循环是同步的。如何使每个循环在执行下一个GET请求之前等待5秒。

 jsons = ["123.com","234.com","456.com"]


    jQuery.each(jsons, function(key,ele) {
    var maindomain = ele; 
    var apis= "https://api.panel.com/search?q="+maindomain;
    $.get(apis, function(source) { 

    if(source == "yes")
    {
    $.get("https://database.com/update.php?domain="+maindomain, function(response) { 
    console.log("successs");
    });
    }

    //SLEEP 5 seconds Here
    });

1 个答案:

答案 0 :(得分:2)

您可以使用.queue() $.when() setTimeout().dequeue()

var jsons = ["123.com","234.com","456.com"];

$({}).queue("requests", jsons.map(function(request) {
  return function(next) {
    // do ajax stuff
    $.get("https://api.panel.com/search?q=" + request)
    .then(function(source) {
       if (source === "yes")
       return $.get("https://database.com/update.php?domain=" + maindomain)
    })         
    .then(function() {
      // call `next` function after `5000ms` timeout
      setTimeout(next, 5000)
    })
  }
})).dequeue("requests")



var jsons = ["123.com","234.com","456.com"], res = [];

var fn = function(arg) {
  return $.Deferred(function(d) {
    d.resolve([arg, "success", {}])
  }).then(function(data) {
    res.push(data); return data
  })
}

$({}).queue("requests", jsons.map(function(request) {
  return function(next) {
    // do ajax stuff here
    fn(request).then(fn.bind(null, request))
    .then(function() {
      console.log(res)
      // call `next` function after `5000ms` timeout
      setTimeout(next, 5000)
    })
  }
})).dequeue("requests")

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
&#13;
&#13;
&#13;