当在while循环中使用promise.all时,会发生MaxListenersExceededWarning

时间:2019-06-01 08:46:15

标签: node.js es6-promise

我在while循环中使用promise。当执行约50个诺言时,MaxListenersExceededWarning警告开始发出警报。所以我想知道EventEmitter和Promise之间是什么关系。以及如何修正我的代码以避免此警告。

我试图减少contentList中的项目数。当数字小于50时,不会发出警告。但是当数字超过五十时,它就会开始发出警告。

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" src='index.css'>
</head>
<body>
  <div id="expandedImage" style="width:800px; height:500px;float:left; 
border: 1px solid black">
  </div>
  <!-- <div id="con"></div> -->
  <div id="main" style="width:150px; height: 500px; overflow-y: 
scroll;float:right"> 
  </div>
  <script src="index.js"></script>
</body
</html>

错误代码

async (req, res, next) => {
    let repository = new ContentRep();

    let contentList = (await repository.getContentList({category: 'allContent'})).contentList;

    while (contentList.length > 0) {
        let taskSize = contentList.length > 5 ? 5 : contentList.length;
        let subList = contentList.slice(0, taskSize);
        contentList = contentList.slice(taskSize, contentList.length);
        let contentPromises = [];

        subList.forEach(row => {
            contentPromises.push(new Promise(resolve => {
                repository.getTemplateInfo(row.category, row.content)
                    .then(templateInfo => {
                        resolve(templateInfo);
                    });
            }));

        })

        await Promise.all(contentPromises);
    }
    return contentList;
}

1 个答案:

答案 0 :(得分:0)

This warning commonly occurs because of memory leakage and internal errors. Increase the limit of maximum events that you can register will remove the warning

Add this code to your main file

require('events').EventEmitter.prototype._maxListeners = 100;