promise学习
const fs = require('fs'); const path = require('path'); fs.readFile(path.join(__dirname, 'data/a.txt'), (err, data)=>{ console.log(data.toString()); fs.readFile(path.join(__dirname, 'data/b.txt'), (err, data)=>{ console.log(data.toString()); fs.readFile(path.join(__dirname, 'data/c.txt'), (err, data)=>{ console.log(data.toString()); }); }); });
const fs = require('fs'); const path = require('path'); // 1. 创建一个promise (一经创建, 立马执行)链式编程 new Promise((resolve, reject)=>{ fs.readFile(path.join(__dirname, 'data/a.txt'), (err, data)=>{ if(err){ reject(err); } resolve(data); }); }).then((data)=>{ console.log(data.toString()); return new Promise((resolve, reject)=>{ fs.readFile(path.join(__dirname, 'data/b.txt'), (err, data)=>{ if(err){ reject(err); } resolve(data); }); }); }).then((data)=>{ console.log(data.toString()); return new Promise((resolve, reject)=>{ fs.readFile(path.join(__dirname, 'data/c.txt'), (err, data)=>{ if(err){ reject(err); } resolve(data); }); }); }).then((data)=>{ console.log(data.toString()); }).catch((err)=>{ console.log(err); });
1 const fs = require('fs'); 2 const path = require('path'); 3 4 let readFile = (...args) => { 5 return new Promise((resolve, reject) => { 6 fs.readFile(...args, (err, data) => { 7 if (err) { 8 reject(err); 9 } 10 resolve(data); 11 }); 12 }); 13 }; 14 15 readFile(path.join(__dirname, 'data/c.txt'), 'utf-8') 16 .then((data) => { 17 console.log(data.toString()); 18 return readFile(path.join(__dirname, 'data/a.txt'), 'utf-8'); 19 }).then((data) => { 20 console.log(data.toString()); 21 return readFile(path.join(__dirname, 'data/b.txt'), 'utf-8'); 22 }).then((data) => { 23 console.log(data.toString()); 24 }).catch((err)=>{ 25 console.log(err); 26 });
1 const fs = require('fs'); 2 const path = require('path'); 3 4 let readFile = (...args) => { 5 return new Promise((resolve, reject) => { 6 fs.readFile(...args, (err, data) => { 7 if (err) { 8 reject(err); 9 } 10 resolve(data); 11 }); 12 }); 13 }; 14 15 Promise.all([ 16 readFile(path.join(__dirname, 'data/aa.txt'), 'utf-8'), 17 readFile(path.join(__dirname, 'data/b.txt'), 'utf-8'), 18 readFile(path.join(__dirname, 'data/c.txt'), 'utf-8') 19 ]).then(([data1, data2, data3])=>{ 20 console.log({data1, data2, data3}); 21 }).catch((err)=>{ 22 console.log(err); 23 });