1
votes

I have a script which reads a CSV file , converst it to json and then i read thru it row by row to check if i have the data already in my DB. So far i can reat the data but my problem is the call to my db. as i want to use await for the db query to come back i wrapped it in an async function.

const processFile = async (file) => {
    var rowcount = 0
    csv()
        .fromFile(file)
        .subscribe(json => { 
            return new Promise((resolve, reject) => {
                console.log(rowcount++ + ' ' + recCount);
                console.log('recProcessed', {rowcount, recCount})
                var result = await db.checkFarmMaster(json.APN)
                console.log(result.recordset[0].RecCount)
                resolve();               
        })
        .then(() => {
            console.log(recCount)              
        })
        .catch(err => {
            console.log(err.message)             
        })
        })}

but that generates the folowing error

var result = await db.checkFarmMaster(json.APN) SyntaxError: await is only valid in async function

when i use it like this it works just fine

const test = async (p_APN) => {
var result = await db.checkFarmMaster(p_APN)
console.log(result.recordset[0].RecCount)
}

So i take it that this is because of the fact its inside a promise.

1
Which csv module are you using? - jfriend00

1 Answers

3
votes

You do not have to use Promise constructor here, just return async function

    .subscribe(async json => { 
        console.log(rowcount++ + ' ' + recCount);
        console.log('recProcessed', {rowcount, recCount})
        var result = await db.checkFarmMaster(json.APN)
        console.log(result.recordset[0].RecCount)
    })