为什么我的代码不等待功能完成?

时间:2018-08-01 13:18:03

标签: 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(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.     
            }
        });             
    });  
}

上面的函数在基类中,并由以下代码调用:

let headerIDs = await self.parseHeaders(mysqlCon, ghID, filePath); 
console.log("headers:",JSON.stringify(headerIDs));

事件的顺序是parseHeaders中的所有内容都已完成,但对self.getParamID的调用除外,并且控制权返回到调用函数,该函数为headerIDs打印一个空数组。 然后,console.log中的self.getParamID语句将被打印。

我想念什么? 谢谢

1 个答案:

答案 0 :(得分:0)

当您要为每一行执行一个异步操作时,我们可以定义一个处理程序以完成此操作:

 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);
    }
 });