js promise分析

面对js的大量回调,如setTimeOut setInterval

代码:

var Pro = function (time) {
    //返回一个Promise对象
    return new Promise(function (resolve, reject) {
        console.log('123');
        //模拟接口调用
        setTimeout(function () {
            //这里告诉Promise 成功了,然后去执行then方法的第一个函数
            resolve('成功返回');
        }, time);
    })
};

function testPromise(){
    Pro(3000).then(function(){
        console.log("then step 1")
      
    }).then(function(){
        console.log("then step 2")
    })
}

结果:

按顺序执行

打印出 step1 step2

发布了53 篇原创文章 · 获赞 2 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/frankxixu/article/details/98324663