Promise简介
promise是es6(es6是2015年发布的)提出来的一个非常重要的语法
promise作用 :
promise是一种解决方案 — 是想编写同步的代码的方式 来处理异步的一种解决方案
用来解决多层回调嵌套
可以把一个多层嵌套的同步 异步都有回调的方法 给拉直为一串.then()组成的调用链
以前处理异步的方式 : 定时器 回调
setTimeout(() => {}, 1000)
$.ajax({
url: '....',
success: res => {}
})
如果异步请求比较简单 单一的话 回调是没有问题的 但是如果异步请求比较复杂 次数比较多 会造成一个 回调地狱
回调地狱缺点
- 代码不优雅 2. 结构不清晰 3. 不容易编写代码
来举个例子:
现在发送个个请求 第一个请求完成了 再请求第二个 再请求第三个。。。 (注意顺序问题)
<!-- 第一个请求 -->
$.ajax({
url :'...',
data : ...,
type : ...,
success : res => {
<!-- 第二个请求 -->
$.ajax({
url :'...',
data : ...,
type : ...,
success : res => {
<!-- 第三个请求 -->
$.ajax({
url :'...',
data : ...,
type : ...,
success : res => {
<!-- 第四个请求 -->
$.ajax({
url :'...',
data : ...,
type : ...,
success : res => {
}
})
}
})
}
})
}
})
解决办法 : 利用 Promise
Promise.then(res => {
// 请求第一个
}).then(res => {
// 请求第二个
}).then(res => {
// 请求第三个
})
- 在此简述下同步异步
// 异步和同步
// 同步 : 阻塞代码
// 异步 : 不阻塞代码
Promise的基本使用
Promise 是一个构造函数 所以可以利用new 实例化出来一个
() 小括号中的参数是一个回调
- resolve : fn - 操作成功调用resolve
- reject : fn - 操作失败调用reject
Promise内部放一个异步操作
const p = new Promise((resolve, reject) => {
setTimeout(() => {
// console.log('异步操作开始了')
// 假如 异步操作成功 => 调 resolve => 走then
// resolve('操作成功了')
// 假如异步操作失败 => 调reject => 走 catch
reject('操作失败...')
}, 0)
})
// 使用
p.then(res => {
console.log('走then了', res)
}).catch(err => {
console.log('走catch了', err)
})
// p 是一个 Promise 类型
// axios.get() 或者 axios.post() 都是promise 类型的
// axios.get().then() => 也就是说 p 也是可以.then()
// 换言之 以后如果出现 XXXX.then() name XXX 可能就是一个promise类型
Promise的链式编程
const p = new Promise((resolve, reject) => {
setTimeout(() => {
// 成功
resolve('成功的数据')
// 失败
// reject()
}, 0)
})
/**
* 1. promise 遵循链式编程
* 2. .then() 里面的res结果 由点then之前的promise内部的resolve 决定的
* 3. 第一个then 里面res1 有值 因为p点的这个then p里面有resolve('成功的数据')
* 第二个then 里面的res2 没有值 因为它之前的promise 是通过.then创建出来的默认 resolve 没有返回数据
* 第三个then也是一样 ...
*/
p.then(res1 => {
console.log('走 then1', res1)
})
.then(res2 => {
console.log('走 then2', res2)
})
.then(res3 => {
console.log('走 then3', res3)
})
// .catch(err => {
// console.log('走catch')
// })
Promise的三个状态
Promise的三个状态
-pending 等待/进行中
-resolved 操作成功
-rejected 操作失败
const p = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('异步操作开始了')
// resolve()
reject()
}, 0)
})
console.log(p)