首页 > 解决方案 > 在 NodeJS 中,我如何等待 http2 客户端库 GET 调用的响应?

问题描述

我正在使用带有 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.jsasync-awaithttp2getmethod

解决方案


如果你想要await它,那么你必须将它封装到一个返回承诺的函数中,然后你可以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 方法是默认方法,这就是为什么没有必要在此处指定它的原因。


推荐阅读