Javascript 双括号在javascript中是什么意思以及如何访问它们
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28916710/
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
What do double brackets mean in javascript and how to access them
提问by Jeff
Situation
情况
I have the following function which uses Promise.
我有以下使用Promise 的函数。
var getDefinitions = function() {
return new Promise(function(resolve) {
resolve(ContactManager.request("definition:entities"));
});
}
var definitions = getDefinitions()
The contents of definitionsis:
内容definitions为:
Promise {
[[PromiseStatus]]: "resolved",
[[PromiseValue]]: child
}
Accessing the PromiseValueproperty directly returns undefined
PromiseValue直接访问属性返回undefined
var value = definitions.PromiseValue; // undefined
Question
题
What do the double brackets [[ ]]mean, and how do I retrieve the value of [[PromiseValue]].
双括号[[ ]]是什么意思,我如何检索[[PromiseValue]].
回答by Benjamin Gruenbaum
What's the stuff inside [[]]
里面是什么东西 [[]]
My question is what do the double brackets [[ ]] mean, and how do I retrieve the value of [[PromiseValue]].
我的问题是双括号 [[]] 是什么意思,以及如何检索 [[PromiseValue]] 的值。
It's an internal property. You cannot access it directly. Native promises may only be unwrapped in thenwith promises or asynchronously in generally - see How to return the response from an asynchronous call. Quoting the specification:
这是内部财产。您无法直接访问它。本机承诺可能只能then与承诺一起或异步展开- 请参阅如何从异步调用返回响应。引用规范:
They are defined by this specification purely for expository purposes. An implementation of ECMAScript must behave as if it produced and operated upon internal properties in the manner described here. The names of internal properties are enclosed in double square brackets [[ ]]. When an algorithm uses an internal property of an object and the object does not implement the indicated internal property, a TypeError exception is thrown.
本规范定义它们纯粹是为了说明目的。ECMAScript 的实现必须表现得好像它以此处描述的方式生成和操作内部属性。内部属性的名称括在双方括号 [[ ]] 中。当算法使用对象的内部属性并且该对象没有实现指定的内部属性时,会抛出 TypeError 异常。
You cannot
你不能
Seriously though - what are they?
说真的 - 它们是什么?
Very nice! As the above quote says they're just used in the spec - so there is no reason for them to really appear in your console.
非常好!正如上面的引述所说,它们只是在规范中使用 - 因此它们没有理由真正出现在您的控制台中。
Don't tell anyone but these are really private symbols. The reason they exist is for other internalmethods to be able to access [[PromiseValue]]. For example when io.js decides to return promises instead of taking callbacks - these would allow it to access these properties fast in cases it is guaranteed. They are notexposed to the outside.
不要告诉任何人,但这些确实是私人符号。它们存在的原因是其他内部方法能够访问[[PromiseValue]]. 例如,当 io.js 决定返回承诺而不是接受回调时 - 这将允许它在保证的情况下快速访问这些属性。它们不会暴露在外面。
Can I access them?
我可以访问它们吗?
Not unless you make your own Chrome or V8 build. Maybe in ES7 with access modifiers. As of right now, there is no way as they are not a part of the specification and will break across browsers - sorry.
除非您制作自己的 Chrome 或 V8 版本。也许在带有访问修饰符的 ES7 中。截至目前,没有办法,因为它们不是规范的一部分,并且会跨浏览器中断 - 抱歉。
So how do I get my value?
那么如何获得我的价值呢?
getDefinitions().then(function(defs){
//access them here
});
But what if it returns an error? In prevision towards these cases, add the following at the end (and outside of) of your .then().
但是如果它返回一个错误呢?在这些情况下,在 .then() 的末尾(和外部)添加以下内容。
.catch(function(defs){
//access them here
});
Although if I had to guess - you're not converting the API correctly to begin withsince this conversion would only work in case the method is synchronous (in that case don't return a promise) or it returns a promise already which will make it resolved (which means you don't need the conversion at all - just return.
尽管如果我不得不猜测 - 您没有正确地开始转换 API,因为这种转换仅在该方法是同步的(在这种情况下不返回承诺)或它已经返回一个承诺的情况下才有效,这将使它已解决(这意味着您根本不需要转换 - 只需return.
回答by cafemike
I also walked into this problem today and happened to find a solution.
我今天也走进了这个问题,碰巧找到了解决方案。
My solution looks like this:
我的解决方案如下所示:
fetch('http://localhost:3000/hello')
.then(dataWrappedByPromise => dataWrappedByPromise.json())
.then(data => {
// you can access your data here
console.log(data)
})
Here, dataWrappedByPromiseis a Promiseinstance. To access the data in the Promiseinstance, I found that I just needed to unwrapthat instance with the .json()method.
这里,dataWrappedByPromise是一个Promise例子。为了访问Promise实例中的数据,我发现我只需要用方法解开那个实例.json()。
Hope that helps!
希望有帮助!
回答by Lachlan Young
Thisexample is with react but for the most part it should be the same.
这个例子是用 react 但在大多数情况下它应该是相同的。
Replacethis.props.url with your url to fetch to make it work for most other frameworks.
将this.props.url替换为您要获取的 url 以使其适用于大多数其他框架。
Parsing the res.json()returns the [[promiseValue]] however if you then return it to another .then()method below you can return it as a total array.
解析res.json()返回 [[promiseValue]] 但是,如果您将其返回到下面的另一个.then()方法,则可以将其作为总数组返回。
let results = fetch(this.props.url)
.then((res) => {
return res.json();
})
.then((data) => {
return data;
})
回答by himanshu verma
Try using await.
尝试使用await。
Instead of
代替
var value = definitions.PromiseValue
use
用
var value = await definiton;
This might solve your purpose by yielding the promise value.
这可能会通过产生承诺值来解决您的目的。
Note thatawait can only be used inside async functions, and it is an ES2016 feature.
请注意,await 只能在异步函数中使用,并且它是 ES2016 的一个特性。
回答by Nit
Reading the manpage, we can see that:
阅读手册页,我们可以看到:
By design, the instant state and value of a promise cannot be inspected synchronously from code, without calling the
then()method.To help with debugging, only when inspecting a promise object manually, you can see more information as special properties that are inaccessible from code(this, at present, is implemented by randomizing the property name, for the lack of more sophisticated language or debugger support).
按照设计,在不调用
then()方法的情况下,无法从代码中同步检查承诺的即时状态和值。为了帮助调试,只有在手动检查 promise 对象时,您才能看到更多信息作为代码无法访问的特殊属性(目前,这是通过随机化属性名称来实现的,因为缺乏更复杂的语言或调试器支持)。
Emphasis mine. Therefore, what you want to do cannot be done. The better question is whydo you need to access the promise state like that?
强调我的。因此,您想做的事情无法完成。更好的问题是为什么你需要像那样访问 promise 状态?
回答by Shun ITOH
I think that it will go well with this.
我认为这会很顺利。
(async () => {
let getDefinitions = await ( () => {
return new Promise( (resolve, reject) => {
resolve(ContactManager.request("definition:entities"));
});
})();
)();
回答by Hari Kiran Mutyala
For the case when the response returned is HTML, not a JSON
对于返回的响应是 HTML 而不是 JSON 的情况
fetch('http://localhost:3000/hello')
.then(response => response.text())
.then(data => {
// you can see your PromiseValue data here
console.log(data)
})

