在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行,在请求完成之前,我看不到阻止的方法。

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

import * as http2 from "http2";
...
function getData(path) {
return new Promise((resolve, reject) => {
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();
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(如果您指定了该选项(,已经为您收集了整个响应,并且已经支持promise(您的代码需要在原始版本中添加的所有内容(。

请注意,GET方法是默认方法,这就是为什么没有必要在此处指定它。

response = await new Promise(async (resolve, reject)=> {
let data = '';
req.on('data', async (chunk) => { 
data += chunk;
resolve(JSON.parse(data));
});
});

最新更新