我觉得这里的事情已经不正常了。我想建立与 mySQL 数据库的连接。然后我想读入一个文件。我想逐行获取名称并运行查询。我会假设我的返回承诺的 sqlSelectQuery 函数会等待承诺解决,然后再移动到下一行。我在这里想念什么?
const mysql = require('mysql');
const fs = require('fs');
const path = require('path');
const csv = require('fast-csv');
const config = require('./config')
const connection = mysql.createConnection({
user: config.user,
password: config.password,
database: config.database,
host: config.host
});
connection.connect((err) => {
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
fs.createReadStream(path.resolve(__dirname,'data.csv'))
.pipe(csv.parse({ headers: true }))
.on('error', error => console.error("error", error))
.on('data', row => { // need to get this to block
sqlSelectQuery(row).then(result => console.log("result: ", result))
})
.on('end', rowCount => console.log(`Parsed ${rowCount} rows`));
const sqlSelectQuery = (row) => {
return new Promise((resolve, reject) => {
console.log("inside promise");
const selectQuery = 'SELECT * FROM loans where business_name = ?;';
connection.query(selectQuery, [row.BorrowerName], (err,rows) => {
let result = {};
if(err) reject(err);
if (rows.length === 1){
let res = rows[0];
result = {
business_name: res.business_name,
loan_range: res.loan_range,
loan_amount: row.InitialApprovalAmount,
count: 1
};
resolve(result);
} else {
result = {
business_name: row.BorrowerName,
loan_range: "",
loan_amount: "",
unique: rows.length
};
resolve(result);
}
});
})
}
my console looks like this
inside promise
inside promise //20 times (I have 20 rows)
Parsed 20 rows
Connection established
result: {....}
result: {...}....