簡體   English   中英

嘗試在node.js中使用promise時出錯

[英]Got error when trying to use promise in node.js

嘗試在模塊頁面上在節點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)
}

這是錯誤

$節點pg1.js

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

await運算符只能在async函數內使用:

檢查此鏈接以獲取更多信息:

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中附帶了異步/等待。

工作示例 (必須使用支持異步/等待功能的瀏覽器,例如Chrome)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM