【问题标题】:How to wait inside multile Jquery Get Function如何在多个 Jquery Get 函数中等待
【发布时间】:2016-03-01 06:54:18
【问题描述】:

在下面的代码中,我循环遍历每个域并通过 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
    });

【问题讨论】:

标签: javascript jquery html json get


【解决方案1】:

您可以使用.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>

【讨论】:

  • database.com/update.php?domain=" + maindomain 应该在第一个 get 请求完成后运行
  • 加一个,你好,我如何为这个sniper添加错误处理
  • @Vishnu 您应该可以将.fail() 添加到第二个.then()
猜你喜欢
  • 2012-04-11
  • 1970-01-01
  • 2015-07-17
  • 2019-01-15
  • 2020-03-07
  • 1970-01-01
  • 2013-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多