【问题标题】:Writing promise based HTTP request using Async/Await使用 Async/Await 编写基于 Promise 的 HTTP 请求
【发布时间】: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


【解决方案1】:

您发布的代码不使用承诺(req 是一个事件发射器,更具体地说是一个ClientRequest 实例),所以不,您不能在这里使用async/await 语法。

我熟悉带有 resolve/reject 的 return new Promise 方法,但我更愿意使用 async/await

不,无论如何您都不能使用async/await 代替Promise constructor。您只能将其用作 then 调用的语法糖。

【讨论】:

  • 感谢您的澄清。干杯
猜你喜欢
  • 2019-05-08
  • 2017-10-29
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多