1.常用用法
//promise主要用来解决低于回调问题
//fs.readFile是一个异步函数,如果直接调用,不使用promise,是无法返回结果
const fs = require('fs')
function getFileByPath(fpath){
//resolve是成功之后的回调函数,reject是失败之后的回调函数
var promise = new Promise(function (resolve,reject) {
fs.readFile(fpath,'utf-8',(err,data)=>{
if(err) return reject(err)
resolve(data)
})
})
return promise
}
//在调用的时候通过.then方法来制定成功和失败的回调函数
getFileByPath('./1.txt').then(function (data) {
console.log(data)
},function(err){
console.log('失败了')
})
2.连续读取3个文件
//连续读取3个文件
const fs = require('fs')
const getFileByPath = function (fpath) {
return new Promise(function (resolve, reject) {
fs.readFile(fpath, 'utf-8', (err, data) => {
if (err) return reject(err)
resolve(data)
})
})
}
//在上一个then中,返回一个新的promise实例。可以继续用下一个.then来处理
getFileByPath('1.txt').then(function (data) {
console.log(data)
return getFileByPath('2.txt')
})
.then(function(data){
console.log(data)
return getFileByPath('3.txt')
})
.then(function (data) {
console.log(data)
})
3.
//连续读取3个文件
//前面读取失败,后面继续执行,可以用.then单独执行每一个失败的回调
const fs = require('fs')
const getFileByPath = function (fpath) {
return new Promise(function (resolve, reject) {
fs.readFile(fpath, 'utf-8', (err, data) => {
if (err) return reject(err)
resolve(data)
})
})
}
//在上一个then中,返回一个新的promise实例。可以继续用下一个.then来处理
getFileByPath('11.txt').then(function (data) {
console.log(data)
}, function (err) {
console.log('读取失败')
return getFileByPath('2.txt')
})
.then(function (data) {
console.log(data)
return getFileByPath('3.txt')
})
.then(function (data) {
console.log(data)
})
4.
//连续读取3个文件
//前面promise执行失败,则立即终止所有promise的执行
const fs = require('fs')
const getFileByPath = function (fpath) {
return new Promise(function (resolve, reject) {
fs.readFile(fpath, 'utf-8', (err, data) => {
if (err) return reject(err)
resolve(data)
})
})
}
//在上一个then中,返回一个新的promise实例。可以继续用下一个.then来处理
getFileByPath('11.txt').then(function (data) {
console.log(data)
})
.then(function (data) {
console.log(data)
return getFileByPath('3.txt')
})
.then(function (data) {
console.log(data)
})
.catch(function (err) {
console.log('catch方法可以捕获错误并阻止后续的执行')
})