簡體   English   中英

NodeJS:等待Promises的所有foreach完成但從未真正完成

[英]NodeJS: Wait for all foreach with Promises to finish but never actually finishes

我正在使用Nodejs。 我有一個異步,因為我必須在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。 我沒有執行打印數組長度的下半部分。

誰能告訴我我做錯了什么? 我是否因為必須在forEach中進行等待而錯誤地使用Promise和forEach?

注意:getCSVList()和getCsv()是從sftp服務器獲取Csvs的函數:

function getCSVList() {
    return new Promise((resolve, reject) => {
            conn.on('ready', function () {
                conn.sftp(function (err, sftp) {
                        if (err) throw err;
                        sftp.readdir(config.development.pathToFile, function (err, list) {
                            if(err) {
                                console.log(err);
                                conn.end();
                                reject(err);
                            } else {
                                console.log('resolved');
                                conn.end();
                                resolve(list);
                            }
                        })
                })
            }).connect({
                host: config.development.host,
                port: config.development.port, // Normal is 22 port
                username: config.development.username,
                password: config.development.password
                // You can use a key file too, read the ssh2 documentation
            });
    })
}

function getCsv(filename) {
    return new Promise((resolve, reject) => {
        conn.on('ready', function () {
        conn.sftp(function (err, sftp) {
            if (err) reject(err);
            let csvFile = sftp.createReadStream(`${config.development.pathToFile}/${filename}`, options);
            // console.log(csvFile);
            conn.end();
            resolve(csvFile);
        })
    }).connect({
        host: config.development.host,
        port: config.development.port, // Normal is 22 port
        username: config.development.username,
        password: config.development.password
        // You can use a key file too, read the ssh2 documentation
    });
});
} 

我的控制台中所有控制台日志的輸出是:

`➜ node server.js
resolved
[ Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> } ]
here`

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);
});


將您的問題分解成碎片,確認它們一直在工作。

除其他外,您沒有正確使用流。

我用ssh2-sftp-client做了一個工作示例,所以你可以用它作為起點。


工作范例:

var fs = require('fs'); var _ = require('underscore');
var SFTPClient = require('ssh2-sftp-client');
const CONFIG = {
 "SSH_CONN_OPTS":{"host":"XXXXXXXX","port":22,"username":"XXXXXXXX","password":"XXXXXXXX"},
 "CSV_DIRECTORY":"/var/www/html"
}
//---------------
//.:The order-logic of the script is here
function StartScript(){
 console.log("[i] SSH Connection")
 LoadValidationFile(()=>{
  InitializeSFTP(()=>{ console.log("[+] SSH Connection Established")
   ListRemoteDirectory((list)=>{ console.log(`[i] Total Files @ ${CONFIG.CSV_DIRECTORY} : ${list.length}`)
    //console.log(list) //:now you have a 'list' of file_objects, you can iterate over to check the filename
    var csvFileList = [] //store the names of the files you will request after
    _.each(list,(list_entry)=>{ console.log(list_entry)
     if(!CONFIG.USED_FILES.includes(list_entry.name)){ csvFileList.push(list_entry.name) }
    }) 
    //:now loop over the new final list of files you have just validated for future fetch 
    GenerateFinalOutput(csvFileList)
   })
  })
 })
}
//.:Loads your validation file
function LoadValidationFile(cb){
 fs.readFile(__dirname+'/temp.json','utf8',(err,data)=>{ if(err){throw err}else{
  var content = JSON.parse(data)
  CONFIG.USED_FILES = content.usedFiles
  cb()
 }})
}
//.:Connects to remote server using CONFIG.SSH_CONN_OPTS
function InitializeSFTP(cb){
 global.SFTP = new SFTPClient();
 SFTP.connect(CONFIG.SSH_CONN_OPTS)
 .then(()=>{cb()})
 .catch((err)=>{console.log("[!] InitializeSFTP :",err)})
}
//.:Get a list of files from a remote directory
function ListRemoteDirectory(cb){
 SFTP.list(`${CONFIG.CSV_DIRECTORY}`)
     .then((list)=>{cb(list)})
     .catch((err)=>{console.log("[!] ListRemoteDirectory :",err)})
}
//.:Get target file from remote directory
function GetRemoteFile(filename,cb){
 SFTP.get(`${CONFIG.CSV_DIRECTORY}/${filename}`)
     .then((data)=>{cb(data.toString("utf8"))}) //convert it to a parsable string
     .catch((err)=>{console.log("[!] ListRemoteDirectory :",err)})
}
//-------------------------------------------
var csvLists = []
function GenerateFinalOutput(csv_files,current_index){ if(!current_index){current_index=0}
 if(current_index!=csv_files.length){ //:loop
  var csv_file = csv_files[current_index]
  console.log(`[i] Loop Step #${current_index+1}/${csv_files.length} : ${csv_file}`)
  GetRemoteFile(csv_file,(csv_data)=>{
   if(csv_data){csvLists.push(csv_data)}
   current_index++
   GenerateFinalOutput(csv_files,current_index)
  })
 }else{ //:completed
  console.log("[i] Loop Completed")
  console.log(csvLists)
 }
}
//------------
StartScript()

祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM