我希望能够链接承诺,以使代码同步。我的问题是,根据第一个$ http请求的结果,我可能想要发送另一个或不。 如果我选择不发送另一个$ http请求,我不需要我的第二个then()
来做任何事情。但由于我的第二个then()
不知道这一切,它仍然挂在那里,所以我想我需要从第一个回来,然后一些假虚拟承诺。但是我还想在第二时间()中认识到这种情况。我想出了从第一种情况返回$ q.when('一些值')。下面是代码:如何从.then返回承诺
$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() {...});
是我希望看到与承诺就解决了价值的东西({isDummy:真}),但我怎么做呢?我在res
参数中获得undefined
。
有一个在你的代码一个错字:'funcrtion' – rmorrin