使用await关键字时出现“意外令牌”错误

时间:2015-12-10 06:14:33

标签: javascript async-await ecmascript-next

我正在尝试使用await关键字(使用Babel)编写一个函数,该关键字利用for循环内的pg-promise library

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 referant为Unexpected token的语法错误。在此上下文中使用await关键字的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

原来这是因为您需要先将函数声明为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(...)

答案 1 :(得分:0)

也可以调用函数async