javascript - 使用 await 关键字时出现“意外 token ”错误

标签 javascript async-await ecmascript-next

我正在尝试使用 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/

相关文章:

javascript - 使用 PHP 和 JQuery 编辑 HTML 表模板

javascript - 对字符数组使用 array.reduce()

visual-studio - 拆解(.NET 4.5 之前)异步/等待堆栈跟踪

c# - 如何使用方法 async Task<string> 并返回字符串,然后如何将该方法的委托(delegate)传递给构造函数并在以后使用它?

javascript - 使用动态导入重写 Firebase 服务

javascript - 随机起始地点蛇

javascript - Angular 2+ 中的 'nested' 组件怎么样?

c# - 在任何情况下,异步等待方法内的对象更改在完成后是否可见?

javascript - React-redux connect HOC 作为类装饰器,@connect

javascript - 直接调用或作为工厂函数调用的 ES.next 装饰器