簡體   English   中英

REST API響應巨大

[英]REST API response is huge

我需要請求一個API端點,該端點返回2015年以來的巨大歷史數據集。

但是,我的數據有問題。

當我使用請求庫時,需要花費一些時間來返回數據集,並且文檔顯示以下內容:

const https = require('https');

var options = {
  "method": "GET",
  "hostname": "rest.coinapi.io",
  "path": "/v1/ohlcv/BITSTAMP_SPOT_BTC_USD/history?period_id=1MIN&time_start=2016-01-01T00:00:00",
  "headers": {'X-CoinAPI-Key': '73034021-0EBC-493D-8A00-E0F138111F41'}
};

var request = https.request(options, function (response) {
  var chunks = [];
  response.on("data", function (chunk) {
    chunks.push(chunk);
  });
});

request.end();

如何創建一個等待響應的異步函數,然后將完整的響應寫入文件(使用fs模塊)?

您可以用Promise封裝整個內容,並在處理.on('end')數據后解決它(這意味着.on('end') ):

const https = require('https');

const options = {
  "method": "GET",
  "hostname": "rest.coinapi.io",
  "path": "/v1/ohlcv/BITSTAMP_SPOT_BTC_USD/history?period_id=1MIN&time_start=2016-01-01T00:00:00",
  "headers": {'X-CoinAPI-Key': '73034021-0EBC-493D-8A00-E0F138111F41'}
};

const getMyDataAsync = opts => new Promise((resolve, reject) => 
  https.request(opts, response => {
    const chunks = [];
    response.on('data', chunk => chunks.push(chunk));
    response.on('end', () => resolve(chunks));
    response.on('error', err => reject(err));
  })
);

現在您可以使用then或async的promise:

try {
  const myData = await getMyDataAsync(options);
} catch(e) { /* handle error here */ }

要么

getMyDataAsync(options)
  .then(myData => { /* your data is right here */ })
  .catch(e => { /* handle error here */ })

暫無
暫無

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

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