分享

ES6语法之异步编程-Promise

 印度阿三17 2020-11-29

Promise

分解异步操作,避免回调地狱

 

           //1.promise
            //分解异步操作,避免回调地狱
            function testMise(value) {
                //resolve成功后回调
                //reject失败后回调
                return new Promise((resolve, reject) => {
                    //模拟异步请求
                    setTimeout(() => {
                        console.log('请求中:', value)
                        if (value > 0) {
                            resolve('请求完成');
                        }
                        if (value < 0) {
                            reject('请求失败'   value);
                        }
                    }, 2000)
                })
            }

            //promis函数返回.then()成功后执行.catch()失败后执行
            testMise(-1).then(res => {
                console.log(res)
            }).catch(err => {
                console.log(err)
            })


2.若有多个异步函数依次执行完成再执行下一个函数时


            //2.若有多个异步函数依次执行完成再执行下一个函数时
            function testEmploy() {
                //使用链式调用
                //注意then()方法里返回的必须是下一个promise函数
                testMise(5).then(res => { //请求中5
                    return testMise(4) //请求中4
                }).then(res => {
                    return testMise(3) //请求中3
                }).then(res => {
                    //请求失败则进入下一个then第二个参数
                    return testMise(-1) //请求中-1
                }).then(res => {
                    console.log(res)
                }, err => {
                    console.log(err) //请求失败-1
                    return testMise(1) //请求中1
                }).then(res => {
                    console.log(res) //请求完成
                }).catch(err => {
                    console.log(err)
                })
            }

            testEmploy();


3.Promise.all

全部异步函数执行完成后再执行then回调

            //3.Promise.all
            // 全部异步函数执行完成后再执行then回调
            //res是返回所有函数的参数的数组,
            Promise.all([testMise(7), testMise(8), testMise(9), testMise(1)]).then(res => {
                console.log('全部执行完成', res)
            })

4.Promise.race

有一个执行完成就执行then回调

            //4.Promise.race
            //有一个执行完成就执行then回调
            //res是返回第一个执行完成的参数
            Promise.race([testMise(11), testMise(12), testMise(13), testMise(14)]).then(res => {
                console.log('有一个执行完成', res)
            })

 

来源:https://www./content-1-768651.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多