haochengz
6/19/2018 - 7:09 PM

Callback, Promise and Async/Await

三种控制异步程序的方法


import fs from 'fs'
import util from 'util'

const path = '/Users/hczhao/code/flow/algor/sort/heap.py'

// -----------------------------------------------------------------------------
// Callback style
fs.readFile(path, (err, data) => {
  if (err) return console.log(err)
  console.log(data.toString())
})

const promiseReadFile = util.promisify(fs.readFile)

// -----------------------------------------------------------------------------
// Promise style
promiseReadFile(path)
  .then(data => {
    console.log(data.toString())
  })
  .catch(err => {
    console.log(err)
  })

// -----------------------------------------------------------------------------
// Async/Await style
const readFileAwait = async (path) => {
  try {
    const data = await promiseReadFile(path)
    console.log(data.toString())  
  } catch(err) {
    console.log(err)
  }
}

readFileAwait(path)