Quesofat
Quesofat

Reputation: 1531

Async Await inside event handler in Node.js

I have the following code:

readInterface.on('line', async (line) => {
    const splitLine = line.split(',')

    const domain = splitLine[0]
    splitLine.shift()

    const query = `INSERT INTO domains (domain, ips) VALUES(?, ?);`;
    try {
      await client.execute(query, [ domain, splitLine ])
    } catch(e) {
        console.log(e)
    }
});

Currently this doesn't work. The code doesn't await before moving on to the next line. How can I change this to await the execute for each query keeping in mind the file is too big for node and cannot be read into memory?

Upvotes: 1

Views: 312

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

If you use the asynchronous iterator of readline, you can, in serial, await each read line and await the database query Promise, so that each goes one-by-one without trying to do all of them all at once:

for await (const line of readInterface) {
    const [domain, ...splitLine] = line.split(',');
    const query = `INSERT INTO domains (domain, ips) VALUES(?, ?);`;
    try {
      await client.execute(query, [ domain, splitLine ])
    } catch(e) {
      console.log(e)
    }
}

Upvotes: 4

Related Questions