简体   繁体   English

访问 Javascript 对象的值

[英]Access the value of a Javascript object

控制台图片

I am working with a function that returns a value to a variable.我正在使用一个将值返回给变量的函数。 When i console log the variable it shows what your seen in the image.当我控制台记录变量时,它会显示您在图像中看到的内容。 i need to get access to the value so I can display it to the user how can i do this?我需要访问该值,以便将其显示给用户,我该怎么做?

this is my code function save(user) {这是我的代码功能 save(user) {

        var response= Restangular.all('admin').post(user).then(function (postedUser) {

            return postedUser;

        });

        console.log(response);
        return response;
    }

reponse is a promise . reponse是一种承诺 You can't (or should not be able to) access the value of a promises directly, since the promise might not be resolved yet.您不能(或不应该)直接访问承诺的值,因为承诺可能尚未解决。

Instead, you have to pass a callback to the promise.相反,您必须将回调传递给承诺。 When the promise is resolved with a value, it passes that value to all attached callbacks.当 promise 用一个值解析时,它将该值传递给所有附加的回调。 In your example, the promise will eventually be resolved with value of postedUser .在您的示例中,promise最终将使用postedUser值解决。

The function that calls save can access the value like so:调用save的函数可以像这样访问值:

save(...).then(function(value) {
  // do something with value here
});

Learn more about promises . 了解有关承诺的更多信息


Note: You can drop the .then inside the function and simplify it to注意:您可以将.then放在函数内并将其简化为

function save(user) {
    return Restangular.all('admin').post(user);
}

since you are passing the identity function to .then .因为您将身份函数传递给.then

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM