Promise含义:
Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大
Promise对象的特点
Promise对象的状态不受外界影响。只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态
一旦状态改变,就不会再变。Promise对象的状态改变,只有两种可能:从pending变为fulfilled和从pending变为rejected
Promise三种状态
pending 准备状态
fulfilled 成功状态(resolve)
rejected 失败状态(reject)
最终只有两个状态,1、准备 2、成功或者失败
示例代码:
// 参数:回调函数
const p = new Promise(function(resolve, reject) {
// 异步操作成功就调用 resolve
// 异步操作失败就调用 reject
setTimeout(function(){
resolve('resolve成功了')
// 参数:表示错误信息
// reject('出错了呀')
}, 2000)
})
// 使用
p.then(function(data) {
// data 表示成功的数据
console.log('p操作成功', data)
return 666
}).then(function(data1) {
console.log(data1)
}).catch(function(err) {
// err 表示错误信息
console.log(err)
})
Promise使用实例(解决了回调地狱问题)
.then方法可以传递两个参数,一个是成功的回调一个是失败的回调
.then方法可以连写,但是连写的时候一定要在上一个.then方法中返回一个新的promise对象
示例代码
function timeout(time){
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve()
},time)
})
}
timeout(1000)
.then(function(){
console.log('1s后执行')
return timeout(1000)
}).then(function(){
console.log('2s后执行')
return timeout(1000)
}).then(function(){
console.log('3s后执行')
})
Promise静态方法Promise.all/race
Promise.all: 在所有的Promise异步操作完成之后,执行某个任务就可以使用Promise.all
Promise.race: 在第一个Promise异步操作完成之后,就执行某个任务
示例代码
function timeout(time){
return new Promise(function(resolve, reject){
setTimeout(function(){
console.log('某个异步操作完成')
resolve(Math.random())
},time)
})
}
var arr = [timeout(1000), timeout(3000), timeout(2000)]
Promise.all(arr).then(function(data){
console.log('所有操作完成',data)
})
Promise.race(arr).then(function(data){
console.log('第一个操作完成', data)
})