既然 Promise 建立的实例,是一个异步操做,那么,这个 异步操做的结果,只能有两种状态:promise
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
部分传入的函数能够为空,便可不写文件读取失败后的操做,
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); })