如何检查Promise是否返回空对象 [英] How to check if a promise returns an empty object

查看:478
本文介绍了如何检查Promise是否返回空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是检查用户是否已登录.加载页面时,将使用诺言来检查当前用户.如果用户未登录,则服务器返回{}.我的问题是我不知道如何检查Promise是否返回空对象{}.

The goal is to check if the user is logged in. When the page is loaded, a promise is used to check the current user. If the user is not logged in, the server returns {}. My problem is that I don't know how to check if the promise returns the empty object {}.

我定义了一个资源:

myapp.factory('User', function($resource) {
    return $resource('/users/:userId', {userId: '@id'}, {
    current: {method:'GET', params: {userId: 'current'}}});
});

在ui-router的resolve属性中使用.解决方法用于向控制器提供数据.

which is used in a resolve property in ui-router. The resolve is used to provide data to my controller.

resolve: {
    user: ['User', function(User) {
        return User.current();
    }]
},
controller : function($scope, $window, user) {
    $scope.user = user;

    $scope.userLoggedIn = !isEmptyObject(user);

    function isEmptyObject(obj) {
        console.log(obj);
        var name;
        for (name in obj) {
        return false;
        }
        return true;
    }                                   
}

快递服务器端定义为:

app.get('/users/current', function(req, res) {
    console.log(req.isAuthenticated());
    console.log(req.user);
    if (req.isAuthenticated()) { 
        res.send(req.user);
    } else {
        console.log("Not Authenticated");
        res.send({});
    }
});

问题在于isEmptyObject函数始终返回true.

The issue is that the isEmptyObject function always returns true.

推荐答案

尝试:

    function isEmptyObject(obj) {

       if (obj.length && obj.length > 0)
           return false;          

       if (obj.length === 0)
          return true;           
    }  

BTW, underscore.js 插件具有自己的方法:

BTW, underscore.js plugin has own method:

isEmpty_.isEmpty(object) 

如果对象不包含任何值(没有可枚举的自身属性),则返回true.

Returns true if object contains no values (no enumerable own-properties).

 _.isEmpty([1, 2, 3]);
 => false

 _.isEmpty({});
 => true

这篇关于如何检查Promise是否返回空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆