我正在尝试使用 await
关键字(使用 Babel)编写一个使用 pg-promise library 的函数在 for
循环中。
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);
}
}
但是,我不断收到语法错误,提示 db
引用是一个 Unexpected token
。在此上下文中使用 await
关键字的正确方法是什么?
最佳答案
原来这是因为你需要声明一个函数为async
才能使用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(...)
关于javascript - 使用 await 关键字时出现“意外 token ”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34194949/