【问题标题】:Javascript: How can I Choose a specific Part from an OutputJavascript:如何从输出中选择特定部分
【发布时间】:2018-06-01 12:10:55
【问题描述】:

简单的问题:

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

没有用...

请帮忙,非常感谢!

【问题讨论】:

  • 请添加minimal, complete and verifiable example 以显示实际问题。
  • 你是如何将对象分配给data的?很可能是您为data 分配了一个promise,而不是promise 的值,它只能异步检索。
  • 您是否调试过代码以查看数据、_v 和正文是否填充了值或未定义?哪个部分“不起作用”?
  • 你是怎么得到data的?
  • console.log("token is"+ data._v.body.access_token); 的输出是什么?它是未定义的吗?你有错误吗?请解释更多,以便我们提供帮助

标签: javascript object output console.log


【解决方案1】:

您所展示的是一个承诺。你可以通过它的then 方法使用这个promise:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-27
      • 2021-03-29
      相关资源
      最近更新 更多