Promise
什么是回调地狱
Promise 的基本使用
.then方法的特性
一.回调地狱
什么是回调地狱:
多层回调函数的相互嵌套,就形成了回调地狱
const fs = require('fs')
fs.readFile('./data/a.txt', 'utf8', (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
fs.readFile('./data/b.txt', 'utf8', (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
fs.readFile('./data/c.txt', 'utf8', (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
}
})
}
})
}
})
回调地狱的缺点:
- 代码耦合性太强,牵一发而动全身,难以维护
- 大量冗余的代码相互嵌套,代码的可读性变差
二.Promise 的基本使用
Promise 是一个构造函数
我们可以创建Promise 的实例
const p = new Promise(function(resolve,reject){})
其中:resolve
代表操作成功之后的回调,reject
代表操作失败之后的回调
Promise.prototype 上包含一个 .then() 方法
每一次new Promise()
构造函数得到的实例对象都可以通过原型链的方式访问到.then()
方法和.catch()
方法,例如 p.then().catch()
.then()方法
可以传入预先指定成功的回调函数.catch() 方法
可以传入预先指定失败的回调函数
三.then方法的特性
如果上一个 .then()
方法中返回了一个新的 Promise 实例对象,则可以通过下一个.then()
继续进行处理。因此, .then() 方法是 Promise 支持链式调用的本质原因
const fs = require('fs')
function getfile(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
}
getfile('./data/a.txt')
.then((data) => {
console.log(data);
return getfile('./data/b.txt')
})
.then((data) => {
console.log(data);
return getfile('./data/c.txt')
})
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
})