使用异步/等待从回调返回对象

问题描述 投票:-1回答:3

我无法使用this question的答案解决此问题,因为代码存在差异。

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

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

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

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

console.log('body',body,);
body {
  "name": "foo",
  "email": "[email protected]",
  "website": "www.example.com",
  ...
}

这是我实际上从result中得到的。

console.log('result',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],
javascript node.js asynchronous callback async-await
3个回答
2
投票

使用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


1
投票

您可以使用节点promisfy中的util

const req = require("request");
const {
    promisfy
} = require("util");

const request = promisfy(req.get); 

module.exports = async (config) => {
    return await request.get(url, options);
};

1
投票

request.get()不会返回承诺,因此其上的await并没有任何用处。如果我每次回答这个问题时都有镍,那我就会有很多镍。 await没有魔法。它所做的就是等待诺言。如果您不兑现承诺,它什么也做不了。

您可能不知道,但是request模块及其派生版本位于maintenance mode中(没有新功能,仅修复了错误)。您可以使用request-promise模块然后摆脱回调,也可以切换到正在积极开发的较新模块,例如got模块。那是我的建议:

const got = require('got');

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

  const result = await got(url, options);

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

而且,我希望您认识到所有async函数都返回一个诺言,因此此函数的调用者必须在返回的诺言上使用await.then()才能使结果超出承诺。


如果您想使用request库,则可以使用request-promise获得该库的已承诺版本:

const rp = require('request-promise');

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

  const result = await rp(url, options);

  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;
}
© www.soinside.com 2019 - 2024. All rights reserved.