使用promise
// promise.js
const fs = require("fs");
const read = function(fileName){
return new Promise((resolve,reject)=>{
fs.readFile(fileName,(err,data)=>{
if (err) {
reject(err);
} else{
resolve(data);
}
});
});
};
read('1.txt').then(res=>{
console.log(res.toString());
return read('2.txt'); // 返回新的数据,然后输出
}).then(res => {
console.log(res.toString());
return read('3.txt');
}).then(res => {
console.log(res.toString());
});
使用generator
// generator.js
const fs = require("fs");
const read = function(fileName){
return new Promise((resolve,reject)=>{
fs.readFile(fileName,(err,data)=>{
if (err) {
reject(err);
} else{
resolve(data);
}
});
});
};
function * show(){
yield read('1.txt');
yield read('2.txt');
yield read('3.txt');
}
const s = show();
s.next().value.then(res => {
console.log(res.toString());
return s.next().value;
}).then(res => {
console.log(res.toString());
return s.next().value;
}).then(res => {
console.log(res.toString());
});
使用async函数
const fs = require("fs");
const read = function(fileName){
return new Promise((resolve,reject)=>{
fs.readFile(fileName,(err,data)=>{
if (err) {
reject(err);
} else{
resolve(data);
}
});
});
};
async function readByAsync(){
let a1 = await read('1.txt');
let a2 = await read('2.txt');
let a3 = await read('3.txt');
console.log(a1.toString());
console.log(a2.toString());
console.log(a3.toString());
}
readByAsync();
async函数在function前面有个async作为标识,意思就是异步函数,里面有个await搭配使用,每到await的地方就是程序需要等待执行后面的程序,await后面的语句可以是promise对象、数字、字符串等。