Promise是ES6新增的一个对象类型,Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolve和reject。它们是两个函数,由 JavaScript 引擎提供,不用自己部署。resolve表示成功时执行,reject则表示失败是执行。

在code中,我们经常会使用promise来解决回调地狱问题。

function fun(cb) {
            setTimeout(() => {
                cb && cb()
            }, 1000);
        }
        fun(_ => {
            console.log(1);
            fun(_ => {
                console.log(2);
                fun(_ => {
                    console.log(3);
                    fun(_ => {
                        console.log(4);
                        fun(_ => {
                            console.log(5);

                        })
                    })
                })
            })
        })

用Promise解决之后如下

 function fun2(){
            return new Promise((resolve,reject)=>{
                setTimeout(() => {
                    resolve()
                }, 1000);
            })
        }

         fun2().then(_=>{
            console.log(1); 
            return fun2()
        }).then(_=>{
            console.log(2); 
            return fun2()
        }).then(_=>{
            console.log(3); 
            return fun2()
        }).then(_=>{
            console.log(4); 
            return fun2()
        }).then(_=>{
            console.log(5); 
            return fun2()
        })
Last modification:September 13, 2019
If you think my article is useful to you, please feel free to appreciate