Javascript 在Node.js上处理昂贵的任务(嵌套for循环)

Javascript 在Node.js上处理昂贵的任务(嵌套for循环),javascript,node.js,Javascript,Node.js,首先,我编写总结的伪代码 const ExcelSheet = new ExcelSheet() // excel.js library const usersWithPlayedGames = await findAllUsers({ include: GameTable }); for (let i = 0; i < usersWithPlayedGames.length; i++) { // Write some user data on Excel. ...

首先,我编写总结的伪代码

const ExcelSheet = new ExcelSheet() // excel.js library

const usersWithPlayedGames  = await findAllUsers({ include: GameTable });

for (let i = 0; i < usersWithPlayedGames.length; i++) {
    // Write some user data on Excel.
    ...
    ...
    for (let j = 0; j < usersWithPlayedGames[i].length; j++) {
        // Write some user's game on Excel
        ...
        ...
        for (let k = 0; k < usersWithPlayedGames[i][j].length; k++) {
            // Write some users's game's company data on Excel
            ...
            ...
        }
    }
}

res.send(ExcelSheet.toFile());
const ExcelSheet=new ExcelSheet()//excel.js库
const usersWithPlayedGames=await findAllUsers({include:GameTable});
for(设i=0;i
实际代码相当长

而且它需要客户机req=>res时间将近15秒

我知道我的问题解决方案不好

我可以用这段代码进行重构

但真正的问题是它阻止了另一个客户端请求

我在谷歌上搜索,找到了几个解决方案

  • Node.js子进程生成
  • 使用回调函数进行Make(我不知道怎么做)
  • 多写一个好的算法
  • Node.js中我缺少的概念是什么

    请帮我个小忙


    谢谢。

    您最好在子进程中或web请求线程之外的其他地方运行此任务,但如果这不是一个选项,您可以使用类似于
    setImmediate

    const ExcelSheet = new ExcelSheet() // excel.js library
    
    const usersWithPlayedGames  = await findAllUsers({ include: GameTable });
    
    const excelLoop = (index) => {
    
      for (let j = 0; j < usersWithPlayedGames[index].length; j++) {
          // Write some user's game on Excel
          ...
          ...
          for (let k = 0; k < usersWithPlayedGames[index][j].length; k++) {
              // Write some users's game's company data on Excel
              ...
              ...
          }
      }
    
      if (index < usersWithPlayedGames.length) {
        setImmediate(() => excelLoop(index + 1))
      }
      else {
        res.send(ExcelSheet.toFile());
      }
    };
    
    excelLoop(0);
    
    const ExcelSheet=new ExcelSheet()//excel.js库
    const usersWithPlayedGames=await findAllUsers({include:GameTable});
    常量excelLoop=(索引)=>{
    for(设j=0;jexcelLoop(索引+1))
    }
    否则{
    res.send(ExcelSheet.toFile());
    }
    };
    excelLoop(0);
    

    在Excel上写一些用户数据。
    在Excel上写一些用户游戏
    在Excel上写一些用户游戏的公司数据
    。。。。有没有一种异步的方法来实现这些?由于您没有显示此代码,因此很难猜测。。。但这将解决
    阻塞另一个客户端请求的问题
    issue@Bravo谢谢你,但是我找不到excel.js库的异步方法。有一些,但是从你当前的代码重构可能太难了。非常感谢。我会关注你的链接