0

我需要请求一个 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模块)的异步函数?

4

1 回答 1

0

你可以用 a 包裹你的整个事情,Promise并在你处理完数据后解决它(这意味着.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));
  })
);

现在你可以使用 promise,使用 then 或 async :

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 */ })
于 2018-08-29T09:25:40.220 回答