使用await关键字时出现“Unexpected token”错误

3

我正在尝试使用await关键字(使用Babel)编写一个函数,在for循环中使用pg-promise库

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 关键字的方法是什么?

2个回答

2
原来这是因为在使用await之前,需要将函数声明为async
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(...)

2
不相关的,但在你的例子中,将格式化参数作为 element 传递与传递 { name: element.name } 相同,因为你已经使用了该元素具有的属性 name ;) - vitaly-t
正因为你正在使用 ES6,你可以通过将 async 替换为 generator,并使用 yield 代替 await 来实现相同的功能,而无需借助 Babel。这也是 Babel 的工作原理,它只是将你的代码翻译成相应的命令。请参考示例 - vitaly-t

0

同时将调用函数也设为async


调用该函数的函数怎么样?它是仅在等待的上一级吗? - The Human Cat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接