Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Unexpected token' error using await keyword

I am trying to write a function using the await keyword (using Babel) that makes use of the pg-promise library inside of a for loop.

import postgres from 'pg-promise';
const pgp = postgres();
const db = pgp(<config options>);
const array = <some array of objects>

for (const element of array) {
    try {
        let test = await db.query('INSERT INTO <table> (name) VALUES (${name})', { name: element.name });
        console.log('test: ', test);
    } catch (err) {
        console.log("error," err);
    }
}

However, I keep getting a syntax error that the db referant is an Unexpected token. What is the correct way to use the await keyword in this context?

like image 266
fox Avatar asked May 27 '26 10:05

fox


1 Answers

Turns out that this is because you need to declare a function as async before you can use await

import postgres from 'pg-promise';
const pgp = postgres();
const db = pgp(<config options>);
const array = [<some array of objects>]

const runQuery = async (array)=> {
    try{
        for (const element of array) {
            const test = await db.query('INSERT INTO <table> (name) VALUES (${name})', { name: element.name });
            return test;
        }
    } catch (err) {
        console.log("error," err);
    }
}

runQuery.then((test)=>console.log('test: ', test)).catch(...)
like image 131
fox Avatar answered Jun 04 '26 22:06

fox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!