您的位置:首页 > Web前端 > Node.js

node-使用promise, generator, async/await 读取文件的方法

2018-02-26 11:51 751 查看
在node中,读取文件的模块是 fs,分为同步读取和异步读取。

const fs = require('fs');

// 同步读取文件
let buf = fs.readFileSync('a.text');

// 异步读取文件
fs.readFile('a.text', (err, data) => {
if (err) {
console.log('读取文件失败');
} else {
console.log(data);
}
});


JavaScript 在发展过程中,共经历了回调函数、Promise 对象、Generator 函数,async 函数来处理异步。我们接下来就来看一下 async 函数如何更优雅的处理异步。假设我们需要分别读取 a、b、c 三个文件,具体代码如下:

对 fs 模块进行 Promise 封装

const readFile = function (src) {
return new Promise((resolve, reject) => {
fs.readFile(src, (err, data) => {
if (err) reject(err);
resolve(data);
});
});
};


Promise 的写法

readFile('a.text').then(data => {
console.log(data.toString());
return readFile('b.text');
}).then(data => {
console.log(data.toString());
return readFile('c.text');
}).then(data => {
console.log(data.toString());
});


Generator 的写法

function * ascReadFile () {
yield readFile('a.text');
yield readFile('b.text');
yield readFile('c.text');
}

let g = ascReadFile();
g.next().value.then(data => {
console.log(data.toString());
return g.next().value;
}).then(data => {
console.log(data.toString());
return g.next().value;
}).then(data => {
console.log(data.toString());
});


async 函数写法

async function asyncReadFile(){
let a = await readFile('a.text');
console.log(a.toString());

let b = await readFile('b.text');
console.log(b.toString());

let c = await readFile('c.text');
console.log(c.toString());
}

asyncReadFile();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nodejs