简体   繁体   English

多个 API 调用的 Nodejs 中的套接字挂断错误

[英]Socket Hangup error in Nodejs for multiple API calls

I am trying to fetch a list of all companies listed in stock market from an external API, and after getting the list, I am trying to fetch all details regarding individual companies including graph data.我正在尝试从外部 API 获取在股票市场上市的所有公司的列表,在获得列表后,我正在尝试获取有关各个公司的所有详细信息,包括图形数据。 It was all working fine.一切正常。 However, today I am getting socket hangup error.但是,今天我收到套接字挂断错误。 I have tried going through other posts here in stackoverflow.我试过在stackoverflow中浏览其他帖子。 However, none of them works.但是,它们都不起作用。

const request = require('request');

const fetchAPI = apiPath => {
    return new Promise(function (resolve, reject) {
        request(apiPath, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                resolve(body);
            } else {
                reject(error);
            }
        });
    });
}


// get list of all companies listed in
const fetchCompanyDetails = () => {
    return new Promise(function (resolve, reject) {
        let details = [];
        fetchAPI('https://api//')
        .then(res => {
            res = JSON.parse(res)
            details.push(res);
            resolve(details);
        })
        .catch(err => {
            console.log("error at fetchcompany details" + err);
        })
    });
}

const getDateAndPriceForGraphData = (graphData) => {
    let res = []
    graphData.forEach(data => {
        let d = {}
        d["x"] = new Date(data.businessDate).getTime() / 1000
        d["y"] = data.lastTradedPrice
        res.push(d)
    })
    return res
}


// get graph data for individual assets
const getGraphDataForAssets = (assetID) => {
    return new Promise((resolve, reject) => {
        let details = {};
        fetchAPI(`https://api/${assetID}`)
        .then(async (res) => {
            res = JSON.parse(res)
            let data = await getDateAndPriceForGraphData(res)
            details = data
            resolve(details);
        })
        .catch(err => {
            console.log("error at getGraphDataForAssets" + err);
        })
    });
}


// fetch data about individual assets
const fetchAssetDetailsOfIndividualCompanies = (assetID) => {
    return new Promise((resolve, reject) => {
        let details = {"assetData" : {}, "graphData": {}};
        fetchAPI(`https://api/${assetID}`)
        .then(async (res1) => {
            res1 = JSON.parse(res1)
            details["assetData"] = res1
            // get graph data
            var graphData = await getGraphDataForAssets(assetID)
            details["graphData"] = graphData
            resolve(details);
        })
        .catch(err => {
            console.log("error at fetchAssetDetailsOfIndividualCompanies" + err);
            reject(err)
        })
    });
}


// returns list of details of all tradeable assets (Active and Suspended but not delisted)
const fetchDetailsForEachCompany = async (companyList) => {
    let result = []

    await Promise.all(companyList.map(async (company) => {
        try {
            // return data for active and suspended assets
            if(company.status != "D") {
                let companyData = await fetchAssetDetailsOfIndividualCompanies(company.id)
                result.push(companyData)
            }
        } catch (error) {
          console.log('error at fetchDetailsForEachCompany'+ error);
        }
    }))
    return result
}


exports.fetchAssetDetails = async () => {
    
    let companyDetails = await fetchCompanyDetails()
    let det = await fetchDetailsForEachCompany(companyDetails[0])

    return det
}

在此处输入图像描述

To expand on what I meant with not needing those new Promise() s, this would be an idiomatic async function refactoring for the above code.为了扩展我不需要那些new Promise()的意思,这将是对上述代码的惯用async function重构。

I eliminated getGraphDataForAssets , since it was eventually not used;我删除了getGraphDataForAssets ,因为它最终没有被使用; fetchAssetDetailsOfIndividualCompanies fetched the same data (based on URL, anyway), and then had getGraphDataForAssets fetch it again. fetchAssetDetailsOfIndividualCompanies获取相同的数据(无论如何基于 URL),然后让getGraphDataForAssets再次获取它。

const request = require("request");

function fetchAPI(apiPath) {
  return new Promise(function (resolve, reject) {
    request(apiPath, function (error, response, body) {
      if (!error && response.statusCode === 200) {
        resolve(body);
      } else {
        reject(error);
      }
    });
  });
}

async function fetchJSON(url) {
  return JSON.parse(await fetchAPI(url));
}

async function fetchCompanyDetails() {
  return [await fetchAPI("https://api//")];
}

function getDateAndPriceForGraphData(graphData) {
  return graphData.map((data) => ({
    x: new Date(data.businessDate).getTime() / 1000,
    y: data.lastTradedPrice,
  }));
}

// fetch data about individual assets
async function fetchAssetDetailsOfIndividualCompanies(assetID) {
  const assetData = await fetchJSON(`https://api/${assetID}`);
  const graphData = getDateAndPriceForGraphData(assetData);
  return { assetID, assetData, graphData };
}

// returns list of details of all tradeable assets (Active and Suspended but not delisted)
async function fetchDetailsForEachCompany(companyList) {
  const promises = companyList.map(async (company) => {
    if (company.status === "D") return null;
    return fetchAssetDetailsOfIndividualCompanies(company.id);
  });
  const results = await Promise.all(promises);
  return results.filter(Boolean); // drop nulls
}

async function fetchAssetDetails() {
  const companyDetails = await fetchCompanyDetails();
  return await fetchDetailsForEachCompany(companyDetails[0]);
}

exports.fetchAssetDetails = fetchAssetDetails;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM