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

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()

node传统读取文件和promise,async await,的更多相关文章

  1. Node.js读取文件内容

    原文链接:http://blog.csdn.net/zk437092645/article/details/9231787 Node.js读取文件内容包括同步和异步两种方式. 1.同步读取,调用的是r ...

  2. vue使用技巧:Promise + async + await 解决组件间串行编程问题

    业务场景描述 大家都通过互联网投递过简历,比如在智联.58.猎聘等平台.投递心仪的职位前一般都需要前提创建一份简历,简历编辑界面常规的布局最上面是用户的个人基本信息,如姓名.性别.年龄.名族等,接着是 ...

  3. promise async await使用

    1.Promise (名字含义:promise为承诺,表示其他手段无法改变) Promise 对象代表一个异步操作,其不受外界影响,有三种状态: Pending(进行中.未完成的) Resolved( ...

  4. 一道题理解setTimeout,Promise,async/await以及宏任务与微任务

    今天看到这样一道面试题: //请写出输出内容 async function async1() { console.log('async1 start'); await async2(); consol ...

  5. angular2 学习笔记 ( Rxjs, Promise, Async/Await 的区别 )

    Promise 是 ES 6 Async/Await 是 ES 7 Rxjs 是一个 js 库 在使用 angular 时,你会经常看见这 3 个东西. 它们都和异步编程有关,有些情况下你会觉得用它们 ...

  6. Promise,async/await解决回调地狱

    先说一下async的用法,它作为一个关键字放到函数前面,用于表示函数是一个异步函数,因为async就是异步的意思, 异步函数也就意味着该函数的执行不会阻塞后面代码的执行. 写一个async 函数 as ...

  7. node.js 读取文件--createReadStream

    createReadStream 是fs模块里面读流的一个方法 这个方法基于fs模块的,所以我们先要引进fs模块 let fs=require("fs"); createReadS ...

  8. node.js 读取文件

    一般用法 var path = require("path"); var fs = require("fs"); //let filePath = path.j ...

  9. ES6 class setTimeout promise async/await 测试Demo

    class Person { async getVersion () { return new Promise((resolve, reject) => { setTimeout(functio ...

随机推荐

  1. leetcode 20 Valid Parentheses 括号匹配

    Given a string containing just the characters '(', ')', '{', '}', '[' and']', determine if the input ...

  2. FFmpeg在ubuntu下安装及使用

    FFmpeg是一套可以用来记录.转换数字音频.视频,并能将其转化为流的开源计算机程序.采用LGPL或GPL许可证.它提供了录制.转换以及流化音视频的完整解决方案.它包含了非常先进的音频/视频编解码库l ...

  3. Linux多线程实践(4) --线程特定数据

    线程特定数据 int pthread_key_create(pthread_key_t *key, void (*destr_function) (void *)); int pthread_key_ ...

  4. Linux IPC实践(5) --System V消息队列(2)

    消息发送/接收API msgsnd函数 int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); 参数 msgid: 由ms ...

  5. Leetcode_88_Merge Sorted Array

    本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41631609 通过本文你可能学到的知识为: (1)当我们遇 ...

  6. UILTView经典知识点练习

    作者:韩俊强   未经允许,请勿转载! 关注博主:http://weibo.com/hanjunqiang 声明:UILTView 指:UILabel 和 UITextField 的复合 #impor ...

  7. Understanding and Using HRMS Security in Oracle HRMS

    Understanding and Using HRMS Security in Oracle HRMS Product:Oracle Human Resources Minimum Version: ...

  8. Ext JS添加子组件的误区

    经常会有人问我,为什么我的Grid不能岁窗口的变得而自动调整.了解后,发现很多人都习惯在渲染子组件的时候将Gird渲染到容器内的一个div里,而这正是问题的所在. 在Ext JS的布局系统中,能控制到 ...

  9. 停止预览时调用Camera.release(), 出现Method called after release()异常问题原因及解决办法

    如下代码: private void stopPreview() { Log.w(TAG, "stopPreview(), _isPreviewing = " + _isPrevi ...

  10. Java-Filter-FilterChain-FilterConfig源码

    public interface Filter { /** * Called by the web container to indicate to a filter that it is being ...