javascript - 使用 async/await 从回调中返回对象
问题描述
我无法用这个问题的答案来解决这个问题,因为代码存在差异。
我想从回调中返回一个对象。当我运行下面的代码时,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
。
body {
"name": "foo",
"email": "foo@example.com",
"website": "www.example.com",
...
}
这就是我真正从中得到的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);
});
});
编辑:
推荐阅读
- python - 运行评估问题 - Tensorflow 对象检测 api (EfficentDet)
- java - 测试登录Servlet
- postgresql - ST_MinimumBoundingCircle 椭圆而不是圆形
- reactjs - Jest/Enzyme:以 withStyles 作为高阶组件的 React 组件中的模拟函数
- c# - 我想生成具有不同运动角度的正方形。我不知道如何描述这个,但我有一个关于这应该如何工作的视频
- sql - 如何从 MS SQL Server 中的表中获取 MAX Id 值
- node.js - Nuxt.js:渲染器资源未加载!请检查可能的控制台错误并确保 dist
- sql - 使用 case 条件连接值
- r - 如何在 ggplot2 中旋转标签?
- forms - MVC 应用程序不会在表单重新编辑上显示选定的值