使用promise须要注意的几点:html
1.如何用promise实现并行的异步 (Promise.all配合.map)
var arr = [] for ( let i = 0; i < 5; i++ ) { arr.push( new Promise( ( resolve ) => { setTimeout( () => { console.log( i ) resolve('结果:' + i) }, i * 1000 ) } ) ) } Promise.all(arr).then(val => { console.log(val) })
2.用Promise串行的异步
3.Promise.race的用法
Promise.race()和all相似,也能够并行,可是它是只要有一个子promise完成了,race()的状态也就完成了。node
应用: 把一个异步操做和定时器放在一块儿。若是定时器先触发就提示用户超时git
let ajaxData = '' const ajax = new Promise( ( resolve ) => { setTimeout( () => { console.log( 'ajax' ) ajaxData = 'ajax' resolve() }, 3000 ) } ) const timer = new Promise( ( resolve ) => { setTimeout( () => { if(ajaxData== ''){ console.log( '用户超时' ) }else{ } resolve() }, 2000 ) } ) Promise.race( [ timer, ajax ] ).then( (data) => { console.log(data) } )
4.什么是值穿透?
.then或者.catch指望传入一个函数,若是不是函数,会发生值穿透github
Promise.resolve(1) .then(2) .then(3) .then(val => { console.log(val) })
5.catch和then的第二个参数的区别?
6.若是catch或者then的第二个参数也抛出异常了,该如何处理?
经过全局添加一个unhandledrejection捕获Promise异常面试
window.addEventListener("unhandledrejection", (e) =>{ console.log(e.reason) }) let promise = new Promise((resolve, reject) => { reject('Hello World') }); promise.catch((err) => { throw('Unexpected Error'); // Unexpected Error })
7.为何then返回的都是Promise对象?
8.一道关于Promise应用的面试题 :红灯三秒亮一次,绿灯一秒亮一次,黄灯2秒亮一次;如何让三个灯不断交替重复亮灯?(用Promse实现)
function tip( timer, fn ) { return new Promise( resolve => { setTimeout( () => { fn() resolve() }, timer ) } ) } function step() { var d = Promise.resolve() d.then( () => { return tip( 3000, () => { console.log( 'red' ) } ) } ) .then( () => { return tip( 1000, () => { console.log( 'green' ) } ) } ) .then( () => { return tip( 2000, () => { console.log( 'yellow' ) } ) } ) .then(() => { step() }) } step()
更多文章,可关注https://github.com/ziwei3749/...ajax
若是有疑问或者发现错误,能够在相应的 issues 进行提问或勘误。数组
若是喜欢或者有所启发,欢迎 star,对做者也是一种鼓励。promise
参考和一些面试题资料 :异步