javascript - Javascript:如何从输出中选择特定部分
问题描述
简单的问题:
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 }
这是我的函数输出,我想指定输出“access_token”我该怎么做?
console.log("token is"+ data._v.body.access_token);
不工作...
请帮助非常感谢!
解决方案
如果您只想拥有 access_token,则可以使用解构
https://developer.mozilla.org/en-US/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
i.e (data) => data.body.access_token
But we can use a new ES6 feature which just returns the object
name passed instead
i.e ({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();
*/
推荐阅读
- html - SVG 标头裁剪位图 - 但具有响应性
- c++ - 如何将 boost 库添加到 Xcode 11?C++
- rust - 将可变数组引用传递给也接受可变数组引用的函数时,为什么没有说明 &mut?
- python - Python 等价于 Javascript querySelector
- android - 在android中,如何对一个类进行单元测试等于另一个类,其中两个类都被包装类包装
- mysql - 返回的日期值与数据库中存储的不同
- python - 将图像中像素的坐标和颜色加载到数组中
- javascript - 显示大数据时 Angular 材质树中的错误
- python - 间距列表值
- java - Retrofit get List 不能用于字符串