【学习笔记】ES6 标准 - Promise、generator
2019-06-21 本文已影响0人
Spidd
const fs = require('fs');
const readFile = function (fileName) {
return new Promise((resovlve, reject)=>{
fs.readFile(fileName,(err,data)=>{
if(err) reject(err);
resovlve(data)
})
})
}
//Promise
readFile('./modules/a.text').then(res=>{
console.log(res.toString());
return readFile('./modules/b.text')
}).then(res=>{
console.log(res.toString())
});
//generator
function * gen() {
yield readFile('./modules/a.text');
yield readFile('./modules/b.text');
}
let g1 = gen();
g1.next().value.then(res=>{
console.log(res.toString())
return g1.next().value;
}).then(res=>{
console.log(res.toString())
})
//async
async function fn() {
let [a,b] = await Promise.all([
readFile('./modules/a.text'),
readFile('./modules/b.text')
]);
console.log(a.toString())
console.log(b.toString())
/*let f1,f2;
try{
f1 = await ;
f2 = await readFile('./modules/b.text');
}catch (e) {
console.log('错误')
}
console.log(f1.toString());
console.log(f2.toString());*/
}
fn();