點燈坊

失くすものさえない今が強くなるチャンスよ

在 Node 使用 Top Level Await

Sam Xiao's Avatar 2021-10-23

Node 14.18.0 總算直接支援 Top Level Await,這使得 await 更加實用,不必再使用 Async Function 配合 IIFE。

Version

Node 14.18.1

Promise

let { Pool } = require ('pg')

let pg = new Pool ({
    host: 'localhost',
    port: 5432,
    user: 'admin',
    password: '12345',
    database: 'KnexLab'
  }
)

pg
  .query ('SELECT * FROM articles')
  .then (x => x.rows)
  .then (console.log)

12 行

pg
  .query ('SELECT * FROM articles')
  .then (x => x.rows)
  .then (console.log)

pg.query 回傳為 Promise,傳統會使用 then 以 synchronous 處理。

Top Level Await

let { Pool } = require ('pg')

let pg = new Pool ({
    host: 'localhost',
    port: 5432,
    user: 'admin',
    password: '12345',
    database: 'KnexLab'
  }
)

;(async function () {
  let { rows } = await pg.query ('SELECT * FROM articles')
  console.log (rows)
}())

12 行

;(async function () {
  let { rows } = await pg.query ('SELECT * FROM articles')
  console.log (rows)
}())

若要使用 await,在 Node 14.18.0 以前則要以 async function 配合 IIFE 才能執行。

ES Module

import PG from 'pg'

let { Pool } = PG

let pg = new Pool ({ 
  host: 'localhost',
  port: 5432,
  user: 'admin',
  password: '12345',
  database: 'KnexLab'
})

let { rows } = await pg.query ('SELECT * FROM articles')
console.log (rows)

13 行

let { rows } = await pg.query ('SELECT * FROM articles')
console.log (rows)

Node 14.8.0 之後可單純使用 top level await,不須再使用 async function + IIFE

{
  "type": "module",
  "name": "node-lab",
  "version": "1.0.0",
  "main": "index.js",
  "dependencies": {
    "pg": "^8.7.1",
  },
  "devDependencies": {
    "nodemon": "^2.0.14"
  },
  "scripts": {
    "serve": "nodemon index.js"
  }
}

第 2 行

"type": "module",

但必須在 package.json 加上 type: module,令 Node 支援 ES Module。

await000

Conclusion

  • 隨著 Node 新版本支援 ES Module 與 top level await,ES Module 將漸漸取代 CommonJS

Reference

Michael Esteban, Top Level Await in Node