使用Async/Await编写基于承诺的HTTP请求
问题描述:
是否可以从节点手册中重写以下HTTP请求示例以使用Async/Await而不是承诺?我熟悉使用解析/拒绝返回新的承诺方法,但宁愿使用异步/等待。使用Async/Await编写基于承诺的HTTP请求
const postData = querystring.stringify({
'msg': 'Hello World!'
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end',() => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
答
您发布不使用承诺的代码(req
是事件发射器,更具体地说是ClientRequest实例),所以没有你不能在这里使用async
/await
语法。 /拒绝
我熟悉
return new Promise
法的决心,但宁可使用异步/等待
不,你不能使用async
/await
而不是Promise
constructor反正。您只能将它作为语法糖用于then
调用。
+0
谢谢你的清晰。干杯 – Kainan
您不能使用'async' /'await' *来代替承诺。您只能使用'async' /'await'语法的promise。 – Bergi
如果它是一个Promise,确定你可以使用'async/await'重写它 – Gerardo