gpt4 book ai didi

javascript - Promise 总是返回初始值

转载 作者:行者123 更新时间:2023-12-03 08:24:21 25 4
gpt4 key购买 nike

AngularJS 中的 Promise 有点问题。我的 promise “被缓存”,这意味着它们总是返回被调用的初始值。我对其他地方的 promise 非常熟悉,但对 angularJS 很陌生,所以请帮助我阐明我的问题,我可能不理解这里非常基本的东西

我正在使用工厂:

.factory('Traffic', function ($http) {
var trafficUrl = 'some url';
var httpPromise = $http.get(trafficUrl, {cache: false} );
var invalidateCache = function() {
return $http.get(trafficUrl, {cache: false} );
}

return {
all: function () {
httpPromise = invalidateCache();
return httpPromise
.then(function (response) {
//parsing the response and returning stuff (not promise)
}

}
})

正在发送请求,并第一次解析它。现在有人建议 invalidateCache 来避免我的问题(每次分配一个新的 $http.get 以避免它引用相同的初始 promise )。

现在我的 Controller :.controller('TrafficCtrl', function ($interval, $ionicLoading, $scope, Traffic) {

var getJams = function () {
var traffic = Traffic.all();
traffic.then(function (response) {
//doing stuff with the response
})
};

$scope.refresh = function () {
getJams();
}
})

现在,每次我调用 $scope.refresh 方法时,我都会看到项目正在“刷新”(console.log 在 getJams 内调用),但值仍保持不变作为第一个调用的 getJams()

谢谢。

最佳答案

从您的评论来看,听起来浏览器正在缓存您的响应,因此您需要更新服务器逻辑以设置缓存特定 header 。

您可能需要将以下 Cache-Control header 添加到您的响应中:

缓存控制:无存储、无缓存

有关缓存 header 的更多信息 here .

应该能够找到大量示例来在您选择的服务器端语言中进行设置。

此外,您还可以进一步清理代码:

.factory('Traffic', function ($http) {
var trafficUrl = 'some url';

return {
all: function () {
// don't need the invalidate call anymore
return $http.get(trafficUrl).then(function (response) {
//parsing the response and returning stuff (not promise)
}

}
})

还有你的 Controller :

var getJams = function () {
// No need to store the initial promise call, just chain them.
Traffic.all().then(function (response) {
//doing stuff with the response
})
};

关于javascript - Promise 总是返回初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33616845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com