尝试在node.js中使用promise时出错

时间:2018-04-07 15:08:15

标签: javascript node.js postgresql promise

尝试在module page中使用节点pg模块上的promise,但是出现了错误。任何评论都表示赞赏。

以下是代码pg1.js

const { Client } = require('pg')
const client= new Client({
  host: 'localhost',
  port: 5432,
  user: 'user1',
  password: 'pass1',
  database: 'staging'
})
await client.connect()
console.log("connected")

x = await client.query("select * from phaas_global.organization")
console.log("x=")
console.log(x)

在我的Mac上运行时出现以下错误。

$ node pg1.js
/Users/user/learn/node/pg1.js:9
await client.connect()
      ^^^^^^
SyntaxError: Unexpected identifier
    at Object.exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:418:7)
    at startup (bootstrap_node.js:139:9)
    at bootstrap_node.js:533:3
MSS1:node user$ node -v
v7.5.0

UPDATE1 我将代码更改为以下内容,仍然会出错。

const { Client } = require('pg')

async connect() {
    const client= new Client({
      host: 'localhost',
      port: 5432,
      user: 'phaasuser',
      password: 'phaaspass',
      database: 'phaas_staging'
    })


    await client.connect()
    console.log("connected")

    x = await client.query("select * from phaas_global.organization")
    console.log("x=")
    console.log(x)
}

这是错误

$ node pg1.js

/Users/user/learn/node/pg1.js:3
async connect() {
      ^^^^^^^
SyntaxError: Unexpected identifier
    at Object.exports.runInThisContext (vm.js:73:16)

1 个答案:

答案 0 :(得分:2)

await运算符只能在async函数中使用:

查看此link了解详情:

async function main() {
    const client = new Client({
        host: 'localhost',
        port: 5432,
        user: 'user1',
        password: 'pass1',
        database: 'staging'
    })
    await client.connect()
    console.log("connected")

    x = await client.query("select * from phaas_global.organization")
    console.log("x=")
    console.log(x)
}

或者您可以将其包装在异步IIFE中:

(async() => {
    // This will be immediately called.
    /*...*/
    await client.connect();
    /* ... */
})();

请注意,节点7.6中已发送async / await。

工作示例(必须使用具有async / await支持的浏览器,例如Chrome)



(async() => {
    // This will be immediately called.
    /*...*/
    const response = await Promise.resolve('I support async/await');
    console.log(response);
    /* ... */
})();