ziwei3749 / blog

已停止更新..转移至 https://segmentfault.com/u/ziwei3749
9 stars 1 forks source link

Promise使用细节 #2

Open ziwei3749 opened 6 years ago

ziwei3749 commented 6 years ago

Promise使用细节

使用promise需要注意的几点:

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()的状态也就完成了。

应用: 把一个异步操作和定时器放在一起。如果定时器先触发就提示用户超时

        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期望传入一个函数,如果不是函数,会发生值穿透

      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()

参考和一些面试题资料 :