我刚看到此代码已被弃用,我一直在尝试按照本指南: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;
}
答案 0 :(得分:2)
在我看来它应该只是:
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)
callback
的返回值将转发到链中的下一个承诺。答案 1 :(得分:1)
另一个答案很接近但是.then
方法回调了一个响应对象,而不是数据。
function fetchPlayers() {
return $http.get(URL)
.then(function onFulfilled(response) {
//DO This
var data = angular.fromJson(response.data);
//NOT This
//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);
}
}
return model.players;
});
}
来自文档:
响应对象具有以下属性:
- data -
{string|Object}
- 使用转换函数转换的响应主体。- status -
{number}
- 响应的HTTP状态代码。- 标题 -
{function([headerName])}
- 标题获取功能。- config -
{Object}
- 用于生成请求的配置对象。- statusText -
{string}
- 响应的HTTP状态文本。