【问题标题】:In NodeJS, how do I await the response of the http2 client library GET call?在 NodeJS 中,我如何等待 http2 客户端库 GET 调用的响应?
【发布时间】:2021-09-28 06:47:58
【问题描述】:

我正在使用带有 nodeJS 的 http2 客户端包。我想执行一个简单的 get 请求,并等待服务器的响应。到目前为止我有

import * as http2 from "http2";
...
 const clientSession = http2.connect(rootDomain);
  ...
  const req = clientSession.request({ ':method': 'GET', ':path': path });
  let data = '';
  req.on('response', (responseHeaders) => {
    // do something with the headers
  });
  req.on('data', (chunk) => {
    data += chunk;
    console.log("chunk:" + chunk);
  });
  req.on('end', () => {
    console.log("data:" + data);
    console.log("end!");
    clientSession.destroy();
  });
  process.exit(0);

但我无法弄清楚的是如何在退出之前等待请求的响应?现在代码飞到 process.exit 行,我看不到阻止的方法,直到请求完成。

【问题讨论】:

    标签: node.js async-await http2 getmethod


    【解决方案1】:

    如果你想await它,那么你必须将它封装到一个返回promise的函数中,然后你可以在该promise上使用await。这是一种方法:

    import * as http2 from "http2";
    ...
    
    function getData(path) {
        return new Promise((resolve, reject) => {
            const clientSession = http2.connect(rootDomain);
            const req = session.request({ ':method': 'GET', ':path': path });
            let data = '';
            req.on('response', (responseHeaders) => {
                // do something with the headers
            });
            req.on('data', (chunk) => {
                data += chunk;
                console.log("chunk:" + chunk);
            });
            req.on('end', () => {
                console.log("data:" + data);
                console.log("end!");
                clientSession.destroy();
                resolve(data);
            });
            req.on('error', (err) => {
                clientSession.destroy();
                reject(err);
            });
        });
    }
    
    async function run() {
        let data = await getData(path);
    
        // do something with data here
    
    }
    
    run().then(() => {
        process.exit(0);
    }).catch(err => {
        console.log(err);
        process.exit(1);
    });
    

    另一种方法是使用更高级别的 http 库,它可以为您完成大部分工作。下面是一个使用got 模块的示例:

    import got from 'got';
    
    async function run() {
        let data = await got(url, {http2: true});
    
        // do something with data here
    
    }
    

    在这种情况下,got() 模块已经为您支持 http2(如果您指定该选项),已经为您收集了整个响应并且已经支持承诺(您的代码需要在原始版本中添加的所有内容) .

    注意,GET 方法是默认方法,所以这里没有必要指定它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多