另一个.js文件中的异步函数在返回时冻结

时间:2019-08-05 13:12:03

标签: javascript node.js

不确定我是否已经了解了整个异步/等待机制。

我的程序:

我有两个文件,(index.js),我正在使用Async函数按顺序触发功能;(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。程序刚刚退出。

1 个答案:

答案 0 :(得分:3)

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

module.exports.downloadAndExtractNewPriceFiles = downloadAndExtractNewPriceFiles();

这就是为什么在尝试在index.js文件中等待的地方不会返回任何承诺,而是应该使用UnhandledPromiseRejection(错误提示downloadAndExtractNewPriceFiles不是函数)的原因引发导致脚本退出。 因此,只需返回该函数即可:

module.exports.downloadAndExtractNewPriceFiles = downloadAndExtractNewPriceFiles;