【问题标题】:async function in another .js file freezing upon return另一个 .js 文件中的异步函数在返回时冻结
【发布时间】:2019-12-13 00:30:57
【问题描述】:

不确定我是否已经完全理解了整个 async / await。

我的程序:

我有两个文件,(index.js)我使用异步函数按顺序触发函数,以及(ftp-download-and-extract.js)包含异步函数downloadAndExtractNewPriceFiles()一个 FTP 服务器,下载最新文件,提取压缩文件,然后将新创建的文件的位置返回给 index.js。

我遇到的问题是我的函数downloadAndExtractNewPriceFiles() 没有返回变量(path_of_extracted_csvs)。没有给出错误信息。

我的猜测是,这与没有完全“获得”异步/等待有关。

// index.js      - used to process functions in order.
const csvToJson = require('csvtojson');
const ftp_download = require('./src/ftp-download-and-extract.js');


(async () => {

    let file_name_array = await ftp_download.downloadAndExtractNewPriceFiles();


    console.log(file_name_array);

})();

// ftp-download-and-extract.js - this is the problem function that isn't returning

const decompress = require('decompress');
const path = require('path');
const fs = require('fs');
const ftp = require("basic-ftp");

const unzipped_directory_path = './src/unzipped/';

let file_obj = require('./FTP_dir_details');  // import file names from JSON file
let Catalogue_WriteStream = fs.createWriteStream(__dirname + '/zipped/catalogue.zip');
let Stock_WriteStream = fs.createWriteStream(__dirname + '/zipped/stock.zip');

let Price_WriteStream = fs.createWriteStream(__dirname + '/unzipped/price.csv');

async function downloadAndExtractNewPriceFiles() {

// function downloadAndExtractNewPriceFiles(){

        console.log('in downloadAndExtractNewPriceFiles function');
        console.log("****************************************");
        console.log("**              PHASE 1               **");
        console.log("**            Starting Up             **");
        console.log("**                                    **");
        console.log("****************************************");
        console.log("");

        let catalogue_csv_path = "";
        let price_csv_path = "";
        let stock_csv_path = "";


        const client = new ftp.Client();
        client.ftp.verbose = true;

        try {
            // Attempt to connect to FTP server

            await client.access({
                host: "x",
                user: "x",
                password: "x",
                secure: false
            });

            // **************************************************************
            //
            // Task 1 - Stock.zip, download and extract
            //
            // **************************************************************

            // Change dir to Catalogue
            await client.cd("/Catalogue");  // Catalogue is also known as 'Non-Components'

            let remote_catalogue_file = file_obj.catalogue_dir_newest_file;

            try {
                // Download file
                await client.download(Catalogue_WriteStream, remote_catalogue_file);

                try {
                    // UnZip file
                    // Maybe use this npm module - utility https://www.npmjs.com/package/node-stream-zip
                    await decompress(Catalogue_WriteStream.path, unzipped_directory_path,).then(files => {
                        console.log('Unzipped : ' + files[0].path);
                        console.log('Task 1 Complete')
                        catalogue_csv_path = files[0].path;  // save to variable where CSV extracted file is.

                    });

                } catch (err) {
                    console.log('Task 1 Failed');
                    console.log("Error cannot unzip file :" + Catalogue_WriteStream.path);
                    console.log(err)
                }


            } catch (err) {
                console.log('Task 1 Failed');
                console.log("Error cannot download file :" + file_obj.catalogue_dir_newest_file);
                console.log(err)
            }


            // Reset to Root Dir
            await client.cd("/");
            // **************************************************************
            //
            // Task 2 - Stock.zip, download and extract
            //
            // **************************************************************

            // Change dir to Stock
            await client.cd("/Stock");


            let remote_stock_file = file_obj.stock_dir_newest_file;

            try {
                // Download file
                await client.download(Stock_WriteStream, remote_stock_file);

                try {
                    // UnZip file

                    await decompress(Stock_WriteStream.path, unzipped_directory_path,).then(files => {
                        console.log('Unzipped : ' + files[0].path);
                        console.log('Task 2 Complete');
                        stock_csv_path = files[0].path;    // save to variable where extracted CSV file is.

                    });

                } catch (err) {
                    console.log('Task 2 Failed');
                    console.log("Error cannot unzip file :" + Stock_WriteStream.path);
                    console.log(err)
                }


            } catch (err) {
                console.log('Task 2 Failed');
                console.log("Error cannot download file :" + file_obj.stock_dir_newest_file);
                console.log(err)
            }

            await client.cd("/");

            // **************************************************************
            //
            // Task 3 - Prices.csv, download and extract
            //
            // **************************************************************
            // IMPORTANT - Price does not need to be decompressed as it is not a ZIP!
            // Change dir to Stock
            await client.cd("/Price");


            let remote_price_file = file_obj.price_dir_newest_file;

            try {
                // Download file
                await client.download(Price_WriteStream, remote_price_file);



            } catch (err) {
                console.log('Task 3 Failed');
                console.log("Error cannot download file :" + file_obj.price_dir_newest_file);
                console.log(err)
            }


        } catch (err) {
            console.log("Operation Failed");
            console.log("Error : Cannot connect to FTP Server");
            console.log(err)

        }


        client.close()
        let new_price_csv_path = path.join(Price_WriteStream.path);
        // let new_price_csv_path = path.join(__dirname, 'unzipped', price_csv_path);
        let new_stock_csv_path = path.join(__dirname, 'unzipped', stock_csv_path);
        let new_catalogue_csv_path = path.join(__dirname, 'unzipped', catalogue_csv_path);


        let path_of_extracted_csvs = [new_price_csv_path, new_stock_csv_path, new_catalogue_csv_path];

        return path_of_extracted_csvs;

    }

module.exports.downloadAndExtractNewPriceFiles = downloadAndExtractNewPriceFiles();

没有错误消息,只是“进程以退出代码 0 完成”,函数的返回不会返回到 index.js。程序刚刚退出。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    在您的模块中,您没有返回函数,而是立即调用它:

    module.exports.downloadAndExtractNewPriceFiles = downloadAndExtractNewPriceFiles();
    

    这就是为什么在您尝试在 index.js 文件中等待它的地方没有返回任何承诺,而是应该抛出一个 UnhandledPromiseRejection(错误是 downloadAndExtractNewPriceFiles 不是函数)导致脚本退出。 所以简单地返回函数应该可以工作:

    module.exports.downloadAndExtractNewPriceFiles = downloadAndExtractNewPriceFiles;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 2020-03-06
      • 2021-07-04
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      相关资源
      最近更新 更多