Javascript: Как я могу выбрать конкретную деталь из вывода - PullRequest
0 голосов
/ 01 июня 2018

простой вопрос:

 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 голосов
/ 01 июня 2018

Вы можете использовать деструктуризацию, если вы просто хотите получить 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();
*/
0 голосов
/ 01 июня 2018

То, что вы показали, это обещание .Вы бы использовали обещание по его then методу:

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

Мы не можем сказать вам, как получить access_token в результате, потому что мы не знаем, какая часть того, что вы 'Показанное значение (если есть) будет значением разрешения.Это может быть result.access_token или result.body.access_token.Но вы не сможете получить к нему доступ, за исключением then обратного вызова.

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