我希望能够链接 promise 以使代码同步。我的问题是,根据第一个 $http 请求的结果,我可能想发送另一个请求,也可能不想发送另一个请求。
如果我选择不发送另一个 $http 请求,我不需要第二个 then()
来执行任何操作。但由于我的第二个 then()
不知道这一切,而且它无论如何都卡在那里,所以我想我需要从第一个然后返回一些虚假的虚拟 promise 。但我也想在第二个 then() 中认识到这种情况。我想出了从第一种情况返回 $q.when('some value') 。这是代码:
$http.get(url, params)
.then(function(res) {
res = res.data;
if (res.status == 'ok' && res.rows.length > 0) {
$scope.roomTypes = res.rows;
return $q.when({ isDummy: true }); //in this case I don't need to send another request
} else if (res.rows.length === 0 && $scope.request.roomType) {
return $http.get(url2, params2); //make second request and return then`able promise
}
}, function(res) {
throw 'Error';
})
.then(function(res) {
res = res.data;
if (res.status == 'ok') {
var roomType = {
room_type: res.roomType.id,
description: res.roomType.description
};
$scope.roomTypes.push(roomType);
} else if (res.isDummy) {
//ok that's our dummy promise
} else {
//format of response unexpected it means something went wrong
throw "error";
}
}, funcrtion(res) {
throw "some Error";
})
.catch(function(res) {...})
.finally(function() {...});
问题是我想查看已解决的 Promise 的值 ({isDummy: true}),但我该怎么做呢?我的 res
参数中出现 undefined
。
最佳答案
res
此处未定义
.then(function(res) {
res = res.data;
...
因为 {isDummy: true}
对象上没有 data
属性。
关于javascript - 如何从 .then 返回 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32715957/