使用javascript promise和setInterval时遇到困难

时间:2013-11-22 12:21:25

标签: javascript jquery promise

我遇到以下javascript问题。我正在使用jQuery框架。

此代码首次运行,核心显示日期,温度和湿度,但第二次运行时出现此错误消息;

未捕获的SyntaxError:意外的标识符

这是代码;

var gettingTemperature = $.post("/get_temperature.php");

setInterval(gettingTemperature, 5000);

gettingTemperature.then(function (data) {

        $('#date').text(data.date);
        $('#temperature').html(data.temperature + "℃");
        $('#humidity').text(data.humidity + "%");

    }, function () {
        console.log('Unable to access temperature model');
    }
);

2 个答案:

答案 0 :(得分:4)

gettingTemperature不代表对$ .post()的调用,而是调用$ .post()的结果,它是jqXHR对象

setInterval需要将函数引用作为第一个参数,但是您可以移交jqXHR对象。这就是为什么你运行$ .post()一次(使用第一行)并且setInterval失败

var gettingTemperature = function {
    $.post("/get_temperature.php").then(function (data) {

        $('#date').text(data.date);
        $('#temperature').html(data.temperature + "℃");
        $('#humidity').text(data.humidity + "%");
    }, function () {
        console.log('Unable to access temperature model');
    });
};

gettingTemperature();
setInterval(gettingTemperature, 5000);

答案 1 :(得分:1)

你应该将方法传递给setInterval,但是你传递了一个承诺。通常在这种情况下,您只需将成功或失败函数传递给$.post调用,但如果您确实需要使用承诺,那也没关系。由于您不确切知道$.post调用何时返回(即需要多长时间),因此您不应该使用setInterval,因为如果它需要的时间超过间隔,则可能会结束多个并发请求,这不是很有用。

在这种情况下,大多数人要做的是等到第一个$.post请求完成,然后在complete处理程序中再次调用$.post。这样你一次只会有一个请求。