在node.js中使用嵌套for循环内的Promise

我仍然在学习Node.js的阶段,我有一个场景在哪里

我有3个表在MySQL 类别子类别项目 ,所有行的名称和ID。

现在,我已经有每个文件夹中的文件夹和一些.xlsx文件的列表以及每个.xlsx文件中的一些工作表

其中foldername是类别表中的类别名称

.xlsx文件名是子类别表中的子类别名称,每个.xlsx文件中的表格名称是项目表格中的项目名称

我想要做的是我需要遍历每个文件夹,文件和工作表,并创build一个Id的映射表。

我的代码到目前为止:

const fs = require('fs'); const path = require('path'); const xlsx = require('node-xlsx').default; const mysql = require('mysql'); const connection = require('./db-connection.js'); var categoryMapping = () => { //directory of all files var mainDirectory = `${__dirname}/xlsx/final_data`; //reading mainDirectory fs.readdir(mainDirectory, function(err, files) { if (err) { console.error("Could not list the directory.", err); process.exit(1); } files.forEach(function(file, index) { //taking the folder name and getting the id of that name var sql = 'SELECT xxx FROM xxx WHERE xxx = ' + mysql.escape(file); connection.query(sql, function(error, result) { if (error) { console.log(error); } if (result.length > 0) { console.log('cat id:', result[0].CategoryId); } else { //fs.appendFile('category.log',`${file} not present in xxx table` + '\n'); console.log(`${file} not present in xxx table`); } }); //directory of .xlxs files var subCategoryDirectory = path.join(mainDirectory, file); fs.readdir(subCategoryDirectory, function(err, sheets) { if (err) { console.error("Could not list the directory.", err); process.exit(1); } sheets.forEach(function(sheet, index) { //taking the file name and getting the id of that name var filename = path.parse(sheet).name; var sql = 'SELECT xxx FROM xxx WHERE xxx = ' + mysql.escape(filename); connection.query(sql, function(error, result) { if (error) { console.log(error); } if (result.length > 0) { console.log('sub cat id:', result[0].SubCategoryId); } else { //fs.appendFile('sub-category.log', `${filename} in ${subCategoryDirectory} not present in xxx table` + '\n'); console.log(`${filename} not present in xxx table`); } }); //individual .xlxs file path var sheetpath = path.join(subCategoryDirectory, sheet); const fileData = xlsx.parse(sheetpath); fileData.forEach(function(page, index) { //taking the sheet name and getting the id of that name var itemName = page.name; var sql = 'SELECT SaltId FROM master_ddb_salts WHERE SaltName = ' + mysql.escape(itemName); connection.query(sql, function(error, result) { if (error) { console.log(error); } if (result.length > 0) { console.log('item id:', JSON.stringify(result[0].ItemId)); } else { //fs.appendFile('salts.log', `${itemName} of ${sheetpath} not present in salt-master table` + '\n'); console.log(`${itemName} not present in xxx table`); } }); //maybe here I need to enter all categoryId, subCategoryId and itemId to mapping table }); }); }); }); }); }; categoryMapping(); 

我的代码到目前为止给我所有的ID正确。

我知道承诺的基本用法,但我没有得到如何在这里实现。

有人能解释我怎么可以在这里使用承诺或callback? 任何更好的解决scheme,如使用像Q,蓝鸟或asynchronousnpm pakages也同样可以。