簡體   English   中英

在 NodeJS 中,我如何等待 http2 客戶端庫 GET 調用的響應?

[英]In NodeJS, how do I await the response of the http2 client library GET call?

我正在使用帶有 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它,那么你必須將它封裝到一個返回承諾的函數中,然后你可以在該承諾上使用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));
        });
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM