const fs = require('fs')
function getFileByPaht(fpath) {
var promise = new Promise(function (resolve, reject) {
fs.readFile(fpath, 'utf-8', (err, dataStr) => {
if (err) return reject(err);
resolve(dataStr);
});
});
return promise;
}
getFileByPaht('./files/3.txt')
.then(function (dataStr) {
console.log(dataStr);
}, function (err) {
console.log(err.message);
})
复制代码
.then()
方法解决地狱回调注意: Promise的
reject
部分传入的函数能够为空,便可不写文件读取失败后的操做,promise
getFileByPath('./files/1222.txt')
.then(function (data) {
console.log(data);
return getFileByPath('./files/2.txt');
},
.then(function (data) {
console.log(data);
return getFileByPath('./files/3.txt');
})
.then(function (data) {
console.log(data);
})
复制代码
状况一:在读取文件出错的部分报错,但不影响后方代码的执行异步
getFileByPath('./files/1222.txt')
.then(function (data) {
console.log(data);
return getFileByPath('./files/2.txt');
}, function (err) {
console.log('读取失败:' + err.message);
return getFileByPath('./files/2.txt');
})
.then(function (data) {
console.log(data);
return getFileByPath('./files/3.txt');
})
.then(function (data) {
console.log(data);
})
复制代码
状况二:若是前面任何的Promise执行失败,就中止运行后面的方法(catch捕获机制)函数
getFileByPath('./files/1222.txt')
.then(function (data) {
console.log(data);
return getFileByPath('./files/2.txt');
})
.then(function (data) {
console.log(data);
return getFileByPath('./files/3.txt');
})
.then(function (data) {
console.log(data);
})
.catch(function (err) {
console.log('异常捕获: ' + err.message);
})
复制代码