dKab dKab - 1 year ago 74
Javascript Question

How to return promise from .then

I want to be able to chain promises in order to make code synchronous. My problem is that depending on result of first $http request I could either be wanting to send another or not.
In case if I choose not to send another $http request I don't need my second

to do anything. But since my second
doesn't know about all this and it's hanging there anyway so I figured I need to return from first then some fake dummy promise. But I would also like to recognize this case in second then() . I came up with returning $q.when('some value') from first case. Here is the code:

$http.get(url, params)
.then(function(res) {
res =;
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 =;
if (res.status == 'ok') {
var roomType = {
description: res.roomType.description
} 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() {...});

The thing is I want to see value with which promise was resolved ({isDummy: true}), but how do I do that? I get
in my

Answer Source

res will be undefined here

      .then(function(res) {
        res =;

because there's no data property on {isDummy: true} object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download