AngularJS: weird console.log behavior with async chrome.storage.local.get()

那年仲夏 提交于 2019-12-11 13:55:25

问题


Let me know if you need more information to solve this issue.

I'm trying to retrieve local data using a factory and calling it from a controller.

Controller.js:

storage.getAllLocalInfo().then(function(data){
    console.log(data.distractions[0].type);
    // produces 'url'
            // console.log(data.distractions);
    // produces the following
    //  0: Object
    //      oldTxt: "youtube.com"
    //      txt: "youtube.com"
    //      type: undefined
    $scope.distractions = data.distractions;
            // This only happens when executing the line above.
    // Without that line, there is no inconsistency.
});

How is it that if I ask for the nested property (type), the console returns the correct value, but when I ask for the entire object, type returns as undefined. This only happens when I include the line with $scope.distractions. And the associated factory:

var getAllLocalInfo = function() {
    var deferred = $q.defer();
    chromeStorage.get( null , function( data ) {
        if (!data) {
            deferred.reject();
        } else {
            deferred.resolve(data);
        }
    });
    return deferred.promise;
};

Can anyone explain the strange behavior of console.log in the controller? I'm also new to promises so that might be what I'm messing up, though this also behaved the same when using a callback in the factory instead of a promise.

来源:https://stackoverflow.com/questions/20910295/angularjs-weird-console-log-behavior-with-async-chrome-storage-local-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!