美文网首页
Node回调函数改写

Node回调函数改写

作者: 毛浩先生 | 来源:发表于2018-06-26 17:25 被阅读0次

以读取文件为例,首先,创建文件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')

相关文章

  • Node回调函数改写

    以读取文件为例,首先,创建文件a.txt,文件内写入内容Hello world!。 回调函数写法 Promise写...

  • nodejs笔记2(回调函数和事件循环)

    回调函数 Node.js 异步编程的直接体现就是回调。Node 使用了大量的回调函数,Node 所有 API 都支...

  • nodejs

    回调函数在完成任务后就会被调用,Node 使用了大量的回调函数,Node 所有 API 都支持回调函数。 NPM ...

  • 回调函数

    Node.js 异步编程的直接体现就是回调。回调函数在完成任务后就会被调用,Node 使用了大量的回调函数,Nod...

  • 07_Node.js Event

    一、回调函数 callback 1、回调函数 Node.js 异步编程的直接体现就是回调,异步编程依托于回调来实现...

  • 回调函数 promise 化

    node 提倡异步回调的事件模型内置异步函数都是回调形式,可以转为 promise, node 提供了内置的工具...

  • node 回调函数

    概念 回调函数在 完成任务后 被 调用。解决阻塞或等待I/O操作,处理大量并发请求。 阻塞代码 非阻塞代码 总结 ...

  • node.js(六)

    Node.js 回调函数Node.js 异步编程的直接体现就是回调。异步编程依托于回调来实现,但不能说使用了回调后...

  • 2020-02-23

    Node.js回调函数 Node.js异步编程的直接体现就是回调 异步编程依托于回调来实现,但不能说使用了回调后程...

  • 04.node内置模块之文件模块fs

    一. 读取文件夹 同步读取文件 异步读取文件夹 异步读取,回调函数后执行 在node中,错误的回调优先,回调函数第...

网友评论

      本文标题:Node回调函数改写

      本文链接:https://www.haomeiwen.com/subject/sbpmyftx.html