定义:用于异步计算
可以将异步操作队列化
可以在对象之间传递和操作Promise,帮助我们处理队列
二.回调有四个问题
1.嵌套层次很深,难以维护
2.无法正常使用return 和 throw
3.难以在多个回调之间
4.无法正常检索堆栈信息
三.promise基本写法
new Promise(
/* 执行器 executor */
function (resolve, reject){
// 一段耗时很长的异步操作
resolve();// 数据处理完成
reject();//数据处理出错
})
.then(function A(){
//成功,下一步
}, function B() {
//失败,做相应处理
})
四.promise嵌套
new Promise( resolve => {
setTimeout( () => {
resolve('hello');
}, 2000);
})
.then( value => {
console.log(value);
return new Promise(resolve=> {
setTimeout( () => {
resolve('world');
}, 2000)
})
})
.then( value => {
console.log(value + 'world')
})
五.错误处理
1.reject(‘error’).then(null,message => {})
2.throw new Error(‘error’).catch(message => {})
推荐使用第二种,更加清晰好读,并且可以捕获前面(then方法)的错误
new Promise( resolve => {
setTimeout( () => {
throw new Error('bye');
}, 2000)
})
.then( value => {
console.log(value + ' world');
})
.catch( error => {
console.log( 'Error: ', error.message);
})
new Promise( (resolve, reject) => {
setTimeout( () => {
reject('bye');
}, 2000)
})
.then( value => {
console.log(value + ' world');
}, value=> {
console.log( 'Error: ', value);
})
Promise.all()
最常见的就是和.map() 连用
new Promise( (resolve, reject) => {
let p1 = new Promise(resolve => {
setTimeout( () => {
resolve('I am P1');
}, 1000)
})
let p2 = new Promise(resolve => {
setTimeout( () => {
resolve('I am P2');
}, 2000)
})
return Promise.all([p1, p2])
})
.then( all => {
console.log(all + ' all');
})
.catch( error => {
console.log( 'Error: ', error.message);
})
实现队列
function queue(things) {
let promise = Promise.resolve();
things.forEach( thing => {
promise = promise.then( () => {
return new Promise( resolve => {
doThing(thing, () => {
resolve();
})
})
})
})
return promise;
}
queue(['lots','of','things',...])
promise.race()
常见用法:
把异步操作和定时器放在一起
如果定时器先触发,就认为超时,告知用户‘网络超时’
实战1
把任何异步操作包装包Promise
假设需求:
用户点击按钮,弹出确认窗体
用户确认和取消有不同的处理
let confirm = popupManager.confirm('您确定么');
confirm.promise
.then( () => {
//do confirm staff
})
.catch( () => {
//do cancel staff
})
//窗体的构造函数
class Confirm {
constructor() {
this.promise = new Promise( (resolve, reject) => {
this.confirmButton.onclick = resolve;
this.cancelButton.onClick = reject;
})
}
}
jQuery已经实现了Promise
IE不支持promise
Promise是用于解决异步计算的一种方式,它可以队列化异步操作,并在对象间传递。回调函数的四个问题包括深嵌套、无法正常return和throw、多回调间的同步困难以及堆栈信息检索难题。Promise的基本写法、嵌套、错误处理(推荐使用catch进行捕获)以及Promise.all()和Promise.race()的常见应用场景进行了介绍。实战示例展示了如何将异步操作包装成Promise来处理用户交互场景,同时提及jQuery已实现Promise但IE不支持。
271

被折叠的 条评论
为什么被折叠?



