ES6 promise简单应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37615202/article/details/88303827
function runAsync() {
   var p = new Promise(function (resolve, reject) {
       //做一些异步操作
       setTimeout(function () {
           console.log('函数里面的执行完成1');
           resolve('随便什么数据1.....');
       }, 2000);
   });
   return p;
}
function runAsync1() {
    var p = new Promise(function (resolve, reject) {
        //做一些异步操作
        setTimeout(function () {
            console.log('函数里面的执行完成2');
            resolve('随便什么数据2.....');
        }, 1000);
    });
    return p;
}
function runAsync2() {
    var p = new Promise(function (resolve, reject) {
        var num = Math.ceil(Math.random() * 10); //生成1-10的随机数
        if (num <= 5) {
            resolve(num);
        } else {
            reject('数字太大了');
        }
    });
    return p;
}
runAsync()
.then(function (data) {
    console.log('this is then....' + data);
    return runAsync1();
})
.then(function (data) {
    console.log('this is then....' + data);
    return runAsync2();
})
.then(function (data) {
    console.log('this is resolve....' + data);
},function (reason, data) {
    console.log('rejected');
    console.log(reason);
})
.catch(function(reason){
    console.log(reason + 'this is cath ....');
})

给个截图: 看一下结果

猜你喜欢

转载自blog.csdn.net/weixin_37615202/article/details/88303827