promise存在的意义分析resolve reject catch

简介 

new Promise(function(resolve,reject){});

状态

  • pending: 初始状态,成功或失败状态。
  • fulfilled: 意味着操作成功完成。对应resolve
  • rejected: 意味着操作失败。对应reject

resolve:使用resolve  状态变为fulfilled会调用第一个函数

var p = new Promise(function (resolve, reject) {
            var timer = setTimeout(function () {
                console.log('执行操作1');
                resolve('这是数据1');
            }, 1000);
        });
p.then(function (data) {
            console.log(data);
            console.log('这是成功操作');
});

//执行操作1
//VM36:8 这是数据1
//VM36:9 这是成功操作

reject:使用reject  会调用第二个的then

var p = new Promise(function (resolve, reject) {
            reject('这是数据2');     
});

p.then(function(data){//状态为fulfilled时执行
            console.log(data);
            console.log('这是成功操作');
        },function(reason){ //状态为rejected时执行
            console.log(reason);
            console.log('这是失败的操作');
});

//这是数据2
//VM42:10 这是失败的操作

catch:catch与reject一样

var p = new Promise(function (resolve, reject) {
              reject('这是数据2');
          });
p.then(function(data){
              console.log(data);
              console.log('这是成功操作');
}).catch(function(reason){
              console.log(reason);
              console.log('这是失败的操作');
});

//VM48:8 这是数据2
//VM48:9 这是失败的操作

目的:解决回调地狱

普通写法

setTimeout(function () {
          console.log('我');
          setTimeout(function () {
              console.log('爱');
              setTimeout(function () {
                  console.log('米');
                  setTimeout(function () {
                      console.log('饭');
                  }, 1000);
              }, 1000);
          }, 1000);
}, 1000);
//3
//VM54:2 我
//VM54:4 爱
//VM54:6 米
//VM54:8 饭

promise写法

function getStr1() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve('我');
        }, 1000);
    });
}
function getStr2() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve('爱');
        }, 1000);
    });
}
function getStr3() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve('米');
        }, 1000);
    });
}
function getStr4() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve('饭');
        }, 1000);
    });
}
getStr1().then(function (data) {
    console.log(data);
    return getStr2();
}).then(function (data) {
    console.log(data);
    return getStr3();
}).then(function (data) {
    console.log(data);
    return getStr4();
}).then(function (data) {
    console.log(data);
})
//Promise {<pending>}
//VM59:30 我
//VM59:33 爱
//VM59:36 米
//VM59:39 饭

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值