Javascript 为什么我的代码不等待函数的完成?
我试图从文件中读取一些数据并将其存储在数据库中。 这是一个更大事务的一部分,我需要返回的ID来执行进一步的步骤Javascript 为什么我的代码不等待函数的完成?,javascript,node.js,async-await,es6-promise,Javascript,Node.js,Async Await,Es6 Promise,我试图从文件中读取一些数据并将其存储在数据库中。 这是一个更大事务的一部分,我需要返回的ID来执行进一步的步骤 async parseHeaders(mysqlCon, ghID, csv) { var self = this; var hIDs = []; var skip = true; var idx = 0; console.log("Parsing headers"); return new Promise(asy
async parseHeaders(mysqlCon, ghID, csv) {
var self = this;
var hIDs = [];
var skip = true;
var idx = 0;
console.log("Parsing headers");
return new Promise(async function(resolve, reject) {
try {
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream(csv)
});
await lineReader.on('close', async function () {
console.log("done: ", JSON.stringify(hIDs));
resolve(hIDs);
});
await lineReader.on('line', async function (line) {
line = line.replace(/\"/g, '');
if (line.startsWith("Variable")) { //Variable,Statistics,Category,Control
console.log("found variables");
skip = false; //Ignore all data and skip to the parameter description.
return; //Skip also the header line.
}
if (!skip) {
var data = line.split(",");
if (data.length < 2) { //Variable section done return results.
console.log("Found sub?",line);
return lineReader.close();
}
var v = data[0];
var bidx = data[0].indexOf(" [");
if (bidx > 0)
v = data[0].substring(0, bidx); //[] are disturbing mysql (E.g.; Air temperature [�C])
var c = data[2];
hIDs[idx++] = await self.getParamID(mysqlCon, ghID, v, c, data);//, function(hID,sidx) { //add data in case the parameter is not in DB, yet.
}
});
} catch(e) {
console.log(JSON.stringify(e));
reject("some error occured: " + e);
}
});
}
async getParamID(mysqlCon,ghID,variable,category,data) {
return new Promise(function(resolve, reject) {
var sql = "SELECT ID FROM Parameter WHERE GreenHouseID="+ghID+" AND Variable = '" + variable + "' AND Category='" + category + "'";
mysqlCon.query(sql, function (err, result, fields) {
if(result.length === 0 || err) { //apparently not in DB, yet ... add it (Acronym and Machine need to be set manually).
sql = "INSERT INTO Parameter (GreenHouseID,Variable,Category,Control) VALUES ("+ghID+",'"+variable+"','"+category+"','"+data[3]+"')";
mysqlCon.query(sql, function (err, result) {
if(err) {
console.log(result,err,this.sql);
reject(err);
} else {
console.log("Inserting ",variable," into DB: ",JSON.stringify(result));
resolve(result.insertId); //added, return generated ID.
}
});
} else {
resolve(result[0].ID); //found in DB .. return ID.
}
});
});
}
事件的顺序是,parseHeaders
中的所有内容都将完成,除了对self.getParamID
的调用外,控件将返回到调用函数,该函数将为headerID
打印空数组。
然后打印self.getParamID
中的console.log
语句
我错过了什么?
谢谢因为您想对每一行执行异步操作,我们可以定义一个处理程序来正确执行:
const once = (target, evt) => new Promise(res => target.on(evt, res));
function mapLines(reader, action) {
const results = [];
let index = 0;
reader.on("line", line => results.push(action(line, index++)));
return once(reader, "close").then(() => Promise.all(results));
}
现在你可以很容易地解决这个问题:
let skip = false;
const hIDs = [];
await mapLines(lineReader, async function (line, idx) {
line = line.replace(/\"/g, '');
if (line.startsWith("Variable")) { //Variable,Statistics,Category,Control
console.log("found variables");
skip = false; //Ignore all data and skip to the parameter description.
return; //Skip also the header line.
}
if (!skip) {
var data = line.split(",");
if (data.length < 2) { //Variable section done return results.
console.log("Found sub?",line);
return lineReader.close();
}
var v = data[0];
var bidx = data[0].indexOf(" [");
if (bidx > 0)
v = data[0].substring(0, bidx); //[] are disturbing mysql (E.g.; Air temperature [�C])
var c = data[2];
hIDs[idx] = await self.getParamID(mysqlCon, ghID, v, c, data);
}
});
let skip=false;
常量hIDs=[];
等待映射行(lineReader,异步函数(line,idx){
行=行。替换(/\“/g'”);
if(line.startsWith(“Variable”){//变量、统计信息、类别、控件
log(“找到的变量”);
skip=false;//忽略所有数据并跳到参数说明。
return;//同时跳过标题行。
}
如果(!跳过){
var数据=行分割(“,”);
if(data.length<2){//Variable section done返回结果。
console.log(“找到子项?”,第行);
返回lineReader.close();
}
var v=数据[0];
var bidx=数据[0]。indexOf(“[”);
如果(bidx>0)
v=数据[0]。子字符串(0,bidx);//[]会干扰mysql(例如:空气温度[ë?½C])
var c=数据[2];
hIDs[idx]=等待self.getParamID(mysqlCon,ghID,v,c,data);
}
});
由于您使用的是async wait,因此无需使用新承诺,承诺的内部函数将按您预期的方式等待,但您面临的问题是返回新承诺请删除返回新承诺(异步函数(解析、拒绝){
和只返回
而不是解析。另外,由于您使用的是异步等待,因此不需要回调函数,我的意思是等待lineReader。on('close');console.log(hIDs)返回hIDs;
这样做了。现在lineReader.on('close')没有等待。@jallmer请查看上面的注释
let skip = false;
const hIDs = [];
await mapLines(lineReader, async function (line, idx) {
line = line.replace(/\"/g, '');
if (line.startsWith("Variable")) { //Variable,Statistics,Category,Control
console.log("found variables");
skip = false; //Ignore all data and skip to the parameter description.
return; //Skip also the header line.
}
if (!skip) {
var data = line.split(",");
if (data.length < 2) { //Variable section done return results.
console.log("Found sub?",line);
return lineReader.close();
}
var v = data[0];
var bidx = data[0].indexOf(" [");
if (bidx > 0)
v = data[0].substring(0, bidx); //[] are disturbing mysql (E.g.; Air temperature [�C])
var c = data[2];
hIDs[idx] = await self.getParamID(mysqlCon, ghID, v, c, data);
}
});