1. 程式人生 > >Node回撥函式改寫

Node回撥函式改寫

以讀取檔案為例,首先,建立檔案a.txt,檔案內寫入內容Hello world!

回撥函式寫法

const fs = require('fs')
fs.readFile('./a.txt', 'utf-8', (err, data) => {
  if (err) throw err
  console.log(data)
})

Promise寫法

const fs = require('fs')
function getTxt (path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf-8'
, (err, data) => { if (err) reject(err) resolve(data) }) }) } getTxt('./a.txt') .then(rst => console.log(rst))

bluebird寫法

const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs'))
fs.readFileAsync('./a.txt', 'utf-8')
  .then(data => console.log(data)
)

Generator寫法

const fs = require('fs')
function getTxt (path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf-8', (err, data) => {
      if (err) reject(err)
      resolve(data)
    })
  })
}
function * fun () {
  yield getTxt('./a.txt')
}
const run = fun()
run.next().
value.then(data => console.log(data))

async/await寫法

const fs = require('fs')
function getTxt (path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf-8', (err, data) => {
      if (err) reject(err)
      resolve(data)
    })
  })
}
async function run (params) {
  const file = await getTxt(params)
  console.log(file)
  return file
}
run('./a.txt')

我的個人部落格:

我的簡書: