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?
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(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With