当前位置: 代码迷 >> 综合 >> node传统读取文件和promise,async await,
  详细解决方案

node传统读取文件和promise,async await,

热度:81   发布时间:2024-01-31 05:07:00.0

先上传统文件加载方式代码,传统方式在处理多层嵌套时代码比较混乱

const fs = require('fs')  //引入文件系统 
 function readFile (cb) {fs.readFile('./package.json',(err,data) => {if(err) return console.log(err) cb(null,data)}) } //回调函数
readFile((err, data) => {if(!err) {data = JSON.parse(data)console.log(data.name)} })

第二阶段 promsie 新建一个promise对象读取文件成功是返回 resolve(data) 失败是返回 rejext, promise.then里可以得到返回结果

function readfileAsync (path) {return new Promise((resolve,reject) => { fs.readFile(path,(err,data) => {if(err){reject(err)} else {resolve(data)} })}) }readfileAsync('./package.json').then(data => {data = JSON.parse(data)console.log(data.name) }) .catch(err => {console.log(err); })

co + generator function

Generator (*)函数是一个普通函数,但是有两个特征。一是,function关键字与函数名之间有一个星号;二是,函数体内部使用yield表达式,定义不同的内部状态,每次调用

解释generator函数执行的简单方法

function* helloWorldGenerator() {yield 'hello';yield 'world';return 'ending'; } var hw = helloWorldGenerator(); hw.next() // { value: 'hello', done: false }
hw.next() // { value: 'world', done: false }
hw.next() // { value: 'ending', done: true }
hw.next() // { value: undefined, done: true }

co.js 保证 *函数中的 yield方法轮循执行,每次执行均返回的是promise对象,这里同时使用 node中的util方法中的promisify 代替传统的promise,nodejs8.0以上

const util = require('util')const co = require('co')co(function *() { let data = yield util.promisify(fs.readFile)('./package.json') //使用node util 中的promisify实例化 fs.readFile方法同时直接返回结果data = JSON.parse(data)console.log(data.name) })

async 加载方式 nodejs7.6以上版本 用async await 把异步加载方式同步的写法实现,实际上是对 promsie的封装

const util = require('util') const readAsync = util.promisify(fs.readFile)async function init () {let data = await readAsync('./package.json')data = JSON.parse(data)console.log(data.name) }init()

 

  相关解决方案