为了账号安全,请及时绑定邮箱和手机立即绑定

NodeJS:等待所有带有 Promise 的 foreach 完成但从未真正完成

NodeJS:等待所有带有 Promise 的 foreach 完成但从未真正完成

皈依舞 2021-06-29 13:39:33
我正在使用 Nodejs。我有一个异步的 forEach,因为我必须在 forEach 中等待结果。因此,我需要等待 forEach 完成,然后继续处理循环的结果。我找到了几种等待 forEach 的解决方案,其中之一是使用 Promises。我做到了,并且创建了这些承诺,但是,forEach(以及承诺)完成后的代码从未真正执行(console.log 未打印)。并且 NodeJS 函数刚刚结束,没有任何错误。这是我的代码:var Client = require('ssh2').Client;// eslint-disable-next-line no-undefvar csv = require("csvtojson");// eslint-disable-next-line no-undefvar fs = require("fs");// eslint-disable-next-line no-undefconst config = require('./config.json');// eslint-disable-next-line no-undefconst 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 中等待?
查看完整描述

2 回答

?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

Promise.all 是一个将返回一个promise 对象的方法,但您不是在等待您的start 方法执行。


function getCSVList() {

  return new Promise((resolve, reject) => {

    setTimeout(() => {

      resolve([1, 2, 3, 4]);

    }, 1000);

  });

}


function getCsv(params) {

  return new Promise((resolve, reject) => {

    setTimeout(() => {

      resolve(params);

    }, 1000);

  });

}


async function start() {

  const list = await getCSVList();

  const promises = list.map(item => {

    return new Promise(async function (resolve, reject) {

      const csvFile = await getCsv(item);

      console.log('here');

      resolve(csvFile);

    });

  });


  return Promise.all(promises);

}


start().then(res => {

  console.log(res);

});


查看完整回答
反对 回复 2021-07-08
  • 2 回答
  • 0 关注
  • 469 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信