首页 > 解决方案 > 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);

不工作...

请帮助非常感谢!

标签: javascriptobjectoutputconsole.log

解决方案


如果您只想拥有 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();
*/


推荐阅读