«

Promise的基本用法

yang 发布于 阅读:417 JS高阶阶段


回调地狱

回调地狱就是回调函数中嵌套回调函数,维护起来特别麻烦,能解决异步的顺序问题

//请求第一个数据
ajax({
    method: 'get',
    url: './data.txt',
    success: function (d) {
        console.log(d);

        //请求第二个数据
        ajax({
            method: 'get',
            url: './data2.txt',
            success: function (d) {
                console.log(d);

                //请求第三个数据
                ajax({
                    method: 'get',
                    url: './data3.txt',
                    success: function (d) {
                        console.log(d);
                    }
                });
            }
        });
    }
});

什么是Promise?

Promise是ES6新增的承诺对象,用于将异步操作的结果传递出来

Promise有三种状态,两个结果:进行中 => 已成功 进行中 => 已失败

Promise对象有三个方法: .then() .catch() .finally()

Promise的基本用法

  <body>
        <script>
            let p1 = new Promise(function (resolve, reject) {
                //异步代码
                setTimeout(function () {
                    if (0) {
                        resolve('请求成功!!!');
                    } else {
                        reject('请求失败???');
                    }
                }, 1000);
            });

            //异步操作成功时,执行then方法
            p1.then(function (res) {
                console.log('成功的方法:', res);
            });

            //异步操作失败时,执行catch方法
            p1.catch(function (res) {
                console.log('失败的方法:', res);
            });

            //不管成功还是失败,都要执行
            p1.finally(function () {
                console.log('不管成功还是失败,都要执行 finally ');
            });
        </script>
    </body>

Promise其它方法

Promise.all() 将所有的Promise对象统一按顺序进行处理

Promise.resolve() 得到一个成功状态的Promise对象

Promise.reject() 得到一个失败状态的Promise对象

Promise.all([p1, p2, p3]).then(datas => {
    console.log(datas);
});

Promise的基本用法

版权所有:微4e
文章标题:Promise的基本用法
除非注明,文章均为 微4e 原创,请勿用于任何商业用途,禁止转载

推荐阅读:


扫描二维码,在手机上阅读
请先 登录 再评论