node.js - 如何将异步等待与 https 发布请求一起使用
问题描述
我正在寻找将 async / await 与 https post 一起使用的方法。请帮帮我。我在下面发布了我的 https 帖子代码片段。如何使用异步等待。
const https = require('https')
const data = JSON.stringify({
todo: 'Buy the milk'
})
const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (d) => {
process.stdout.write(d)
})
})
req.on('error', (error) => {
console.error(error)
})
req.write(data)
req.end()
解决方案
基本上,您可以编写一个返回 a 的函数,Promise
然后您可以将async
/await
与该函数一起使用。请看下面:
const https = require('https')
const data = JSON.stringify({
todo: 'Buy the milk'
});
const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
},
};
async function doSomethingUseful() {
// return the response
return await doRequest(options, data);
}
/**
* Do a request with options provided.
*
* @param {Object} options
* @param {Object} data
* @return {Promise} a promise of request
*/
function doRequest(options, data) {
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
res.setEncoding('utf8');
let responseBody = '';
res.on('data', (chunk) => {
responseBody += chunk;
});
res.on('end', () => {
resolve(JSON.parse(responseBody));
});
});
req.on('error', (err) => {
reject(err);
});
req.write(data)
req.end();
});
}
推荐阅读
- c# - 如何确定合并范围内的哪些单元格可见并且可以有值?
- angular - 合并 observables 但同时返回
- ms-access - MS Access:在两个表中查找具有不同字段的行
- java - 无法使用 Intent 启动服务,无法添加窗口 - 令牌 null 无效,您的活动是否正在运行?
- php - 如何在没有 eval() 的情况下在 php 中创建动态链接
- excel - 保护关于单元格格式/边框的数据表
- ios - UINavigationController 无法同时推送两个 vc
- java - 如何使用 Spring 通过响应式 websocket 推送数据以响应请求?
- android - ionic cordova 运行 android 失败。不推荐使用未处理的承诺拒绝
- dart - 如何在 Flutter 上创建多个 Shared-Preferences?