promise()的理解和使用

promise用来处理异步代码 Promise的构造函数接收一个参数,是函数,并且传入两个参数:resolve,reject,分别表示异步操作执行成功后的回调函数和异步操作执行失败后的回调函数。按照标准来讲,resolve是将Promise的状态置为fullfiled,reject是将Promise的状态置为rejected。

 function getData() {
            setTimeout(function () {
                var name = 'tom';
                return name;
            }, 1000)
        }
        console.log(getData());  // undefined; 一开始以为能获取到tom  异步

使用回调方法 获取异步方法里面的数据

 function getData1(callback) {
            setTimeout(function () {
                var name = 'tom';
                callback(name);
            }, 1000)
        }

        getData1(function (val) {
            console.log(val);    // tom
        });

使用promise方法 获取异步方法里面的数据

 //使用promise方法 获取异步方法里面的数据
        var p = new Promise((resolve, reject) => {
            setTimeout(function () {
                var count = 0;

                if (count) {
                    resolve(count);
                } else {
                    reject(count);
                }
            }, 1000)
        });

        p.then(res => {           //异步调用
            console.log(res);
        }, err => {
            console.log(err)
        })

        console.log(1);     //比then先执行,也就证明then是异步调用

then链式调用

 //then链式调用
        p.then(res => {
            console.log(res);
            return new Promise((resolve, reject) => {
                resolve('需再return promise对象,才能继续then调用')
            })
        })
            .then(res => {
                console.log(res) // 需要return p.....
            })

err & catch 谁会捕捉reject?

 p.then(res => {
        }, err => {
            // 当同时存在,会直接走then的err回调函数, catch不执行
            console.log('then的', err);
        }).catch(err => {
            console.log('cathc的', err);
        })

promise对象提供了then,catch, all, race方法

1.all方法的传递参数需要是数组;
2.all方法的所有promise是并发执行(同时执行);
3.任何一个promise返回reject,就会中断去执行catch

promise.all()是将所有的参数接口都调用 返回出结果后再返回 并且按照参数顺序返回结果数组

promise.race()是异步调用 哪个接口返回值快 就返回哪个接口的数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值