Javascript:如何从输出中选择特定部件

时间:2018-06-01 12:10:56

标签: javascript object output console.log

简单的问题:

 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);

不起作用......

请帮助非常感谢!

2 个答案:

答案 0 :(得分:0)

您所展示的是承诺。您可以通过then方法使用承诺:

data
.then(function(result) {
    // Use result here
})
.catch(function(err) {
    // Handle error here
});

我们无法告诉您如何访问结果access_token,因为我们不知道您所展示的内容的哪一部分(如果有的话)将是分辨率值。 可能result.access_tokenresult.body.access_token。但是除了then回调之外,您无法访问它。

data
.then(function(result) {
    console.log(result.body.access_token);
})
.catch(function(err) {
    // Handle error here
});

答案 1 :(得分:0)

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