javascript 如何访问 JSON Object.$$state.value?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30146045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access JSON Object.$$state.value?
提问by Ray Zhang
Warning: I'm going to sound like I have no idea what I'm talking about here, because I kind of don't. I'm in the process of self-learning Javascript and AngularJS through a lot of trial and error coding.
警告:我听起来好像不知道我在说什么,因为我有点不知道。我正在通过大量的试错编码自学 Javascript 和 AngularJS。
I have some javascript code (hesitant to copy here because it's a mess) that returns an Object with the following structure:
我有一些 javascript 代码(犹豫是否复制到这里,因为它很乱),它返回一个具有以下结构的对象:
What I want to save to a variable is the object corresponding to Object.$$state.value in the picture. This object has username, hash and salt, which are what I care about. I don't know what all the other stuff like $$state are or how they got there.
我要保存到变量中的是图片中Object.$$state.value对应的对象。这个对象有用户名、哈希和盐,这是我关心的。我不知道像 $$state 这样的所有其他东西是什么,也不知道它们是如何到达那里的。
However, if I do this (let's call the main Object "whatIHave"):
但是,如果我这样做(让我们称主对象为“whatIHave”):
var whatIWant = whatIHave.$$state.value;
this does not work. whatIWant is null.
这不起作用。whatIWant 为空。
Does anyone recognize what's going on here? What is $$state, how did it get there, and how can I extract the value I want?
有人知道这里发生了什么吗?什么是 $$state,它是如何到达那里的,以及如何提取我想要的值?
回答by Jesus Rodriguez
So that is a promise. You need to do something like:
所以这是一个承诺。您需要执行以下操作:
whatIHave.then(function(whatIWant) {
// Work here
});
I highly recommend you to research what a promise is (like this link)
我强烈建议你研究一下承诺是什么(比如这个链接)
If you're curious enough, about what is that $$state
and what is that value
, I will explain a bit:
如果你足够好奇,关于那是$$state
什么,那是什么value
,我会解释一下:
The promises have a $$state
and there angular saves all the callback functions you want to call in a pending
array (all those function you registered with .then
like I explained before).
承诺有一个,$$state
并且 angular 将所有你想调用的回调函数保存在一个pending
数组中(所有你注册的函数,.then
就像我之前解释的那样)。
It also have the status: resolved (1) and rejected (2)
它还具有以下状态:已解决 (1) 和已拒绝 (2)
Finally, when you resolve
or reject
the promise, the value you pass when doing that, is saved in value
.
最后,当您resolve
或reject
承诺时,您在执行此操作时传递的值保存在value
.
You're trying to cheat in here, because when you try to access that value
, it could be not there yet (that is what async
is all about).
你试图在这里作弊,因为当你试图访问它时value
,它可能还不存在(这async
就是全部)。
So the idea is learning the basic of promises, learning how to work with them and then use your whatIHave
correctly.
所以我们的想法是学习 Promise 的基础知识,学习如何使用它们,然后whatIHave
正确地使用它们。