使用Async / Await编写基于promise的HTTP请求
是否有可能从节点手册重写以下HTTP请求示例以使用Async / Await而不是承诺? 我熟悉返回新的承诺方法与决心/拒绝,但宁愿使用asynchronous/等待。
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
方法与解决/拒绝,但宁愿使用asynchronous/等待
不,不能使用async
/ await
而不是Promise
构造函数 。 你可以使用它作为语法糖, then
调用只。