Node.js获取SWAPI结果返回内存错误

时间:2019-08-26 14:53:18

标签: javascript node.js ubuntu async-await out-of-memory

我试图了解Node.js的异步功能。我正在尝试从虚拟数据源(在这种情况下为SWAPI)中获取数据,并在有请求时返回结果。

我在路由器内部的功能是;

const url = "https://swapi.co/api/people/?page="
    const getData = async (url, page) => {
        let n = []
        try {
            const response = await axios.get(url + page);
            const data = response.data;
            for (let i = 0; i < data.results.length; i++) {
                n.push(data.results[i].name)
            }
            return n;
        } catch (error) {
            console.log(error);
        }
    };
    const getAllData = async () => {
        const firstPage = await getData(url, 1);
        const secondPage = await getData(url, 2);
        let allPages = firstPage.concat(secondPage);
        for (var i = 0; iDisplayStart< i < iDisplayLength; i++) {
            aaData.push([
                iDisplayStart + i,
                iDisplayStart + i,
                allPages[i]
            ]);
        }
        var ret = {
            sEcho: "",
            iTotalRecords: 600000,
            iTotalDisplayRecords: aaData.length,
            aaData: aaData
        };
        return res.json(ret);
    }
    getAllData()

但是当我对此端点进行呼叫时,计算机将冻结。因此,我开始从顶部菜单查看内存状态,并从终端运行Node后端服务器。现在它返回下面的错误,我不知道该如何解决这个问题。

  

致命错误:CALL_AND_RETRY_LAST分配失败-JavaScript堆内存不足

1: node::Abort() [node]   
2: 0x55d4acb8a011 [node]   
3: v8::Utils::ReportOOMFailure(char const*, bool) [node]   
4: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [node]  
5: v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationSpace) [node]   
6: v8::internal::Runtime_AllocateInTargetSpace(int, v8::internal::Object**, v8::internal::Isolate*) [node] 
7: 0x2a52e9040bd Aborted (core dumped)

1 个答案:

答案 0 :(得分:0)

让我们放置这段代码,然后执行一些循环。

const getData = async (url, page) => {
  try {
    const nums = [];
    const response = await axios.get(url + page);
    const { data } = response;
    for (let i = 0; i < data.results.length; i += 1) {
      const obj = data.results[i];
      nums.push(obj.name);
    }
    return nums;
  } catch (error) {
    console.log(error);
    throw error;
  }
};

const getAllData = async () => {
  const url = 'https://swapi.co/api/people/?page=';
  const firstPage = await getData(url, 1);
  const secondPage = await getData(url, 2);
  const allPages = firstPage.concat(secondPage);
  console.log(allPages);
  return allPages;
};

const result = getAllData();
console.log(result);