脚本一直运行到尝试关闭数据库连接为止,现在它给了我一个Promise错误。
当我注释掉本节时,脚本可以正常运行而没有错误,但是,数据库连接永远不会关闭...
> // .then(() => {
> // database.close();
> // }, err => {
> // return database.close().then(() => {throw err; });
> // })
在promise链的末尾仅有一个catch块还不够吗?
我收到以下错误:
[错误](节点:9376)UnhandledPromiseRejectionWarning:未处理 承诺拒绝。此错误是由以下原因引起的: 一个没有catch块的异步函数,或者通过拒绝一个Promise 无法使用.catch()处理。 (拒绝ID:1) [[09:33:03.101]] [错误](节点:9376)[DEP0018]弃用警告: 已弃用未处理的诺言拒绝。将来,保证 未处理的拒绝将终止Node.js进程 退出代码为非零。
mysql.js
const mysql = require("mysql");
const mySQLConnectionDetails = {
host: "localhost",
user: "xxxx",
password: "xxxx",
database: "amdm",
multipleStatements: true
};
class Database {
constructor(config) {
this.connection = mysql.createConnection(config);
}
query(sql, args) {
return new Promise((resolve, reject) => {
this.connection.query(sql, args, (err, rows) => {
if (err)
return reject(err);
resolve(rows);
});
});
}
close() {
return new Promise((resolve, reject) => {
this.connection.end(err => {
if (err)
return reject(err);
resolve();
});
});
}
}
module.exports = { Database, mySQLConnectionDetails };
index.js
require("console-stamp")(console, "[HH:MM:ss.l]");
const express = require("express");
const router = express.Router();
const { Database, mySQLConnectionDetails} = require("../helpers/mySQL");
const { cleanseString, cleanseStringToArray, generateCountDuplication, sortValuesBykey, generateScoreArray, calculateAverage, replaceAbbreviationWithExpansion } = require("../helpers/stringFixers");
const database = new Database(mySQLConnectionDetails);
/* GET Clean original name of part and store it in database. */
router.get("/createcleanname", (req, res) => {
let allParts = [];
let eClassCodes = []; // here I define eClassCodes
let abbreviationsAndExpansions = [];
database.query("SELECT * FROM partnumbersclassified")
.then(rows => {
console.log(rows.length);
allParts = rows;
return database.query("SELECT * FROM amdm.abbreviationexpansion");
})
.then(rows => {
abbreviationsAndExpansions = rows;
return database.query("SELECT * FROM eclasstree WHERE numberofdigits = '8'");
})
.then(rows => {
eClassCodes = rows; // Here I assign the values to the variable.
const replaceAbbreviations = replaceAbbreviationWithExpansion(allParts, abbreviationsAndExpansions);
console.log("replaceAbbreviations finished");
const cleanseStrings = cleanseString(replaceAbbreviations, "cleanname");
console.log("cleanseStrings finished");
return cleanseStrings;
})
.then(result => {
result.forEach(obj => {
return database.query(`UPDATE partnumbersclassified SET cleanname = '${obj.cleanname}' WHERE itemnumber = '${obj.itemnumber}'`);
});
console.log("cleanname updated on all parts");
})
.then(() => {
database.close();
}, err => {
return database.close().then(() => {throw err; });
})
.catch(err => {throw err;});
});