[英]Javascript: How can I Choose a specific Part from an Output
easy question: 一个简单的问题:
FunctionOutput: Promise {
_c:
[ { promise: [Object],
resolve: [Function],
reject: [Function],
ok: [Function],
fail: [Function],
domain: null } ],
_a: undefined,
_s: 1,
_d: true,
_v:
{ body:
{ token_type: 'bearer',
access_token: 'token',
expires_in: 7776000,
refresh_token: 'token' },
statusCode: 200 },
_h: 0,
_n: true }
This is my Output from a function and I want to specify output "access_token" How do I do that? 这是我从函数中获得的输出,我想指定输出“ access_token”。我该怎么做?
console.log("token is"+ data._v.body.access_token);
does not work... 不起作用...
Pls help Thanks a lot! 请帮助非常感谢!
What you've shown is a promise . 你展示的是一个承诺 。 You'd use the promise via its then
method: 您可以通过then
方法使用promise:
data
.then(function(result) {
// Use result here
})
.catch(function(err) {
// Handle error here
});
We can't tell you how to access access_token
on the result, because we don't know what part of what you've shown (if any) will be the resolution value. 我们无法告诉您如何访问结果的access_token
,因为我们不知道您显示的内容的哪一部分(如果有)将是分辨率值。 It may be result.access_token
, or result.body.access_token
. 可能是result.access_token
或result.body.access_token
。 But you won't be able to access it except in a then
callback. 但是除非在then
回调中,否则您将无法访问它。
data
.then(function(result) {
console.log(result.body.access_token);
})
.catch(function(err) {
// Handle error here
});
You can use destructuring if you just want to have the access_token 如果您只想拥有access_token,则可以使用解构
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
// whatever you're calling that returns that object const mockRequest = () => new Promise(resolve => resolve(res)) // response const res = { body: { token_type: 'bearer', access_token: 'token', expires_in: 7776000, refresh_token: 'token' }, statusCode: 200 } /* calls async function it then waits until its finsihed the request and "then" calls the then with the data Normally we would just return what ever comes back ie (data) => data.body.access_token But we can use a new ES6 feature which just returns the object name passed instead ie ({body}) => { token_type: 'bearer' ... */ function getAccess() { mockRequest() .then(({body: {access_token}}) => console.log(access_token)) .catch(err => console.log(err)) } getAccess(); /* // Or using es7 features such as async await async function getAccessES7() { const {body:{access_token}} = await mockRequest(); return access_token; } getAccessES7(); */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.