es6的Promise(承诺)

es6的Promise(承诺)

Promise中的所有回调函数,都是异步执行的
//用来解决异步的一些问题
let p = new Promise(function(resolve,refused){
    console.log("abc");
    //resolve();
    setTimeout(function(){
        resolve();
    },3000); 
    console.log("123");
});

p.then(function(){
    console.log("def");
});

//挂起状态     成功状态      失败状态

setTimeout(function(){
    console.log(1);
    setTimeout(function(){
        console.log(2);
        setTimeout(function(){
            console.log(3);
            setTimeout(function(){
                console.log(4);
                setTimeout(function(){
                    console.log(6);
                },5000);
            },3000);
        },3000);
    },2000);
},1000);

function sleep(times){
    return new Promise(function(resolve,refused){
        setTimeout(function(){
            resolve();
        },times);
    });
}

let pr = new Promise(function(resolve,refused){
    setTimeout(function(){
        resolve();
    },1000);
});

pr.then(function(){
    console.log(1);
    return sleep(2000);
}).then(function(){
    console.log(2);
    return sleep(3000);
}).then(function(){
    console.log(3);
    return sleep(4000);
}).then(function(){
    console.log(4);
});



let p3 = new Promise(function(resolve,refused){
    resolve();
    refused("失败了");
});
p3.then(function(){
    console.log("edf");
}).catch(function(e){
    console.log(e);
});
ES6 对 Promise 有了原生的支持,一个 Promise 是一个等待被异步执行的对象,当它执行完成后,其状态会变成 resolved 或者 rejected。
每一个 Promise 都有一个 .then 方法,这个方法接受两个参数,第一个是处理 resolved 状态的回调,一个是处理 rejected 状态的回调
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值