在while循环中延迟 [英] Deferred in a while loop

查看:423
本文介绍了在while循环中延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想在jquery中执行一个延迟的ajax请求,直到收到特定的服务器响应(非null).我将如何去做?

So I want to do a deferred ajax request in jquery until I receive a specific server response (non-null). How would I go about doing that?

while (data.response != null) {
  $.ajax(..).done(function(data);
}

function doUntilResult() {
    Server.doA().done(function(data) {
      Server.doB(data).done(function(result) {
          //if result == null, repeat again
      });
    });
}

推荐答案

要进行较大程度的控制,请写doUntilResult()接受:

To give a large measure of control, write doUntilResult() to accept :

  • 一个doThis回调函数,该函数确定要执行的操作以及重试/终止条件.
  • 一个整数,它确定两次呼叫之间的延迟.
  • a doThis callback function, which determines what is to be done, and the re-try/terminate condition.
  • an integer, which determines the delay between calls.
function doUntilResult(doThis, t) {
    function delay() {
        return $.Deferred(function(dfrd) {
            window.setTimeout(dfrd.resolve, t);
        });
    }
    function poll() {
        return $.when(doThis()).then(function(data) { // $.when() caters for non-async functions to be passed.
            return (data === null) ? delay().then(poll) : data; // continue on null, otherwise return data.
        });
    }
    return poll();
}

现在,您有了通用的doUntilResult()函数,可以在不重写的情况下改变主意,直到完成".一切都在一个(或多个)呼叫中指定.

Now, you have a generalised doUntilResult() function, making it possible to change your mind about what is to be "done until" without re-writing. Everything is specified in the call (or calls).

对于原始问题,请致电:

For the original question, call as follows :

doUntilResult(function() {
    return $.ajax(..).then(function(data) {
        return data || null; // adjust as required to ensure that `null` is returned only for the "continue" condition.
    });
}, 1000); // 1 second delay between calls

对于已编辑的问题,请致电:

For the edited question, call as follows :

doUntilResult(function() {
    return Server.doA().then(function(data) {
        return Server.doB(data);
    }).then(function(result) {
        return result || null; // adjust as required ...
    });
}, 1000); // 1 second delay between calls

无论您想做什么,请始终确保回调的.then链终止于一个函数,只要轮询继续进行,该函数将返回null.

Whatever you want to do, always ensure that the callback's .then chain terminates in a function that returns null whenever the poll is to continue.

这是一个简单的演示,它会生成一个0-10的随机数; 9或更大的数字被视为数据;低于9将会重试. (在控制台中监控进度).

Here's a simple demo which generates a random number from 0-10; numbers of 9 or greater are treated as data; under 9 will cause a re-try. (Monitor progress in console).

这篇关于在while循环中延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆