Promise函数的理解

Promise接收两个参数, 这个两个参数都是函数 , 第一个函数如果执行就会把第一个函数里传递的实参保存到then的形参里 , 同理 , 如果第二个函数执行就会把第二个函数里传递的实参保存到catch的形参里!

/**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        new Promise(
            function (success, fail) {
                var timeOut = 0.5;
                setTimeout(function () {
                    if (timeOut < 1) {
                        success('成功');
                    }
                    else {
                        fail("失败");
                    }
                }, timeOut * 1000);
            }
        ).then(function (res) {
            console.log('then: ' + res);
        }).catch(function (reason) {
                 console.log('catch: ' + reason);
        });
         
    },

同样的 , 这两个只会有一个执行 , 如果你先执行了success('成功') , 然后紧接着执行 fail("失败") , 那么也只会执行最前面的成功的那句 , 反之亦然
也就是说success()和fail()都可以去执行 , 但是你传递的实参只会要么给then传递了 , 要么就给catch传递了 , 绝不会两个都传递 , 传递谁取决于你让谁先在Promise的执行函数里了! 第一个参数先执行就会是then , 第二个先执行就会是catch

onLoad: function (options) {
        new Promise(
            function (success, fail) {
                let timeOut;
                setTimeout(function () {
                    fail("失败");
                    success('成功');
                }, 1000);
            }
        ).then(function (res) {
            console.log('then: ' + res);
        }).catch(function (reason) {
            console.log('catch: ' + reason);
        });

    },

但是如果你很奇怪的先.catch再.then , 并且先执行了第二个函数的话 , 就会回调回来catch的数据 , 然后也会走一遍then , 只不过then没有回调数据而已 , 不建议大家瞎搞~
就会如下图所示:

image.png

onLoad: function (options) {
        new Promise(
            function (success, fail) {
                let timeOut;
                setTimeout(function () {
                    fail("失败");
                    success('成功');
                }, 1000);
            }
        ).catch(function (reason) {
            console.log('catch: ' + reason);
        }).then(function (res) {
            console.log('then: ' + res);
        });

    },

但是你还是先执行成功 , 再执行失败 , 就算你先catch再then也是只执行then不执行catch
如下图所示:

image.png

onLoad: function (options) {
        new Promise(
            function (success, fail) {
                let timeOut;
                setTimeout(function () {
                    success('成功');
                    fail("失败");
                }, 1000);
            }
        ).catch(function (reason) {
            console.log('catch: ' + reason);
        }).then(function (res) {
            console.log('then: ' + res);
        });

    },

愿编程让这个世界更美好

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容