【发布时间】:2018-01-22 22:17:08
【问题描述】:
是否可以重写 Node 手册中的以下 HTTP 请求示例以使用 Async/Await 而不是 Promise?我熟悉使用 resolve/reject 的 return new promise 方法,但更愿意使用 async/await。
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();
【问题讨论】:
-
你不能使用
async/await代替承诺。您只能使用具有async/await语法的 Promise。 -
如果它是 Promise,请确保您可以使用
async/await重写它
标签: javascript node.js