javascript - 如何从 .t​​hen 返回 promise

标签 javascript angularjs promise q deferred

我希望能够链接 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 - 如何从 .t​​hen 返回 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32715957/

相关文章:

javascript - 在jquery中实现圆形滚动条

javascript - 在 div 元素上调整大小

javascript - 从类方法中使用jquery悬停

javascript - 观察对象数组中每个对象的特定属性 - Angular Material

javascript - Typescript 的导入无法解析外部模块

javascript - 在 JavaScript 间隔内等待

javascript - 来自 jquery jtable 的 ajax 调用的错误处理

javascript - Angularjs 指令替换文本

reactjs - 在 React 中使用 Firebase Promise setState

javascript - 如果 then 处理程序不返回任何内容,链式 Promise 的解析值是多少?