我正在使用 Nodejs。我有一个异步的 forEach,因为我必须在 forEach 中等待结果。因此,我需要等待 forEach 完成,然后继续处理循环的结果。我找到了几种等待 forEach 的解决方案,其中之一是使用 Promises。我做到了,并且创建了这些承诺,但是,forEach(以及承诺)完成后的代码从未真正执行(console.log 未打印)。并且 NodeJS 函数刚刚结束,没有任何错误。
这是我的代码:
var Client = require('ssh2').Client;
// eslint-disable-next-line no-undef
var csv = require("csvtojson");
// eslint-disable-next-line no-undef
var fs = require("fs");
// eslint-disable-next-line no-undef
const config = require('./config.json');
// eslint-disable-next-line no-undef
const os = require('os');
let headerRow = [];
let sumTxAmount = 0;
const filenameShortened = 'testFile';
let csvLists = [];
let csvFile;
const options = {
flags: 'r',
encoding: 'utf8',
handle: null,
mode: 0o664,
autoClose: true
}
var conn = new Client();
async function start() {
const list = await getCSVList();
let content = fs.readFileSync('./temp.json', 'utf8');
content = JSON.parse(content);
var promises = list.map(function(entry) {
return new Promise(async function (resolve, reject) {
if (!content['usedFiles'].includes(entry.filename)) {
const filename = entry.filename;
csvFile = await getCsv(filename);
csvLists.push(csvFile);
console.log('here');
resolve();
} else {
resolve();
}
})
});
console.log(promises)
Promise.all(promises)
.then(function() {
console.log(csvLists.length, 'length');
})
.catch(console.error);
}
start();
"here" 打印一次(不是数组长度为 8 的 8 次),但是创建了 8 个 promise。不执行我打印数组长度的下部。
谁能告诉我我做错了什么?我是否错误地使用了 Promises 和 forEach,因为我必须在 forEach 中等待?
哈士奇WWW
相关分类