gpt4 book ai didi

javascript - q.defer deferred.resolve 已弃用

转载 作者:行者123 更新时间:2023-11-28 18:41:19 27 4
gpt4 key购买 nike

我刚刚看到此代码已被弃用,我一直在尝试遵循此指南:http://www.codelord.net/2015/09/24/$q-dot-defer-youre-doing-it-wrong/以正确的方式使用它,但我似乎无法让它工作。有人可以帮我吗?

function fetchPlayers(callback) {

var deferred = $q.defer();

$http.get(URL)
.success(function (response) {
var data = angular.fromJson(response);
for (var g = 0; g < data.player.length; g++) {
var player = model.findPlayerByName(data.player[g].name);
if (player == null) {
var newPlayer = {
_id: (new Date).getTime(),
name: data.player[g].name,
position: data.player[g].position,
};
model.players.push(newPlayer);
}
}
deferred.resolve(model.players);
});
return deferred.promise;
}

最佳答案

在我看来,它应该是:

function fetchPlayers(callback) {
return $http.get(URL)
.then(function (response) {
var data = angular.fromJson(response.data);
for (var g = 0; g < data.player.length; g++) {
var player = model.findPlayerByName(data.player[g].name);
if (player == null) {
var newPlayer = {
_id: (new Date).getTime(),
name: data.player[g].name,
position: data.player[g].position,
};
model.players.push(newPlayer);
}
}
return model.players;
});
}

基本上,

  • 将所有 promise.success(callback) 更改为 promise.then(callback)
  • 直接返回 Promise,而不是创建一个额外的延迟对象,该对象会在第一个 Promise 解析时得到解析。
  • (注意)callback 的返回值被转发到链中的下一个 Promise。

关于javascript - q.defer deferred.resolve 已弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36023576/

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