使用async/await从回调返回对象 [英] Returning an object from a callback using async/await

查看:658
本文介绍了使用async/await从回调返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法通过

I can't resolve this question with the answers to this question because there are differences in the code.

我想从回调中返回一个对象.当我运行以下代码时,body对象的日志看起来像预期的那样.它似乎是正确的JSON对象,其中包含我想要来自服务器的响应:名称,电子邮件,网站等.

I want to return an object out of a callback. When I run the below code, the log of the body object looks as expected. It appears to be the correct JSON object containing the response I want from the server: name, email, website, etc.

但是result对象似乎包含有关请求本身的信息,而不是响应对象.

But the result object appears to contain information about the request itself instead of the response object.

如何返回body对象,以便可以从result变量访问它?

How do I return the body object so that I can access it from the result variable?

const request = require('request'); // npm i request -s

module.exports = async config => {
  ...

  const result = await request.get( url, options,
    ( error, response, body, ) => {
      console.log( 'body', body, ); // I want the other log to look like this log.
      return body;
    }
  );

  console.log( 'result', result, ); // I want this log to look like the above log.
  // In other words, I want the below line to be the name, email, website JSON object
  // contained in the body
  return result;
}

这就是我想要的result.

body {
  "name": "foo",
  "email": "foo@example.com",
  "website": "www.example.com",
  ...
}

这是我实际上从result那里得到的.

This is what I actually get from result.

result Request {
  _events: [Object: null prototype] {
    error: [Function: bound ],
    complete: [Function: bound ],
    pipe: [Function]
  },
  _eventsCount: 3,
  _maxListeners: undefined,
  uri: Url {
    protocol: 'https:',
    slashes: true,
    auth: null,
    host: 'api.example.com',
    port: 443,
    hostname: 'api.example.com',
    hash: null,
  },
  callback: [Function],
  method: 'GET',
  readable: true,
  writable: true,
  explicitMethod: true,
  _qs: Querystring {
    request: [Circular],
    lib: { formats: [Object], parse: [Function], stringify: [Function] },
    useQuerystring: undefined,
    parseOptions: {},
    stringifyOptions: {}
  },
  _auth: Auth {
    request: [Circular],

推荐答案

使用Promise:

const result = await new Promise((resolve) => {
  request.get(url, options, (error, response, body) => {
      console.log( 'body', body );
      resolve(body);
    });
});

或者您可以安装 https://github.com/request/request-promise

这篇关于使用async/await从回调返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆