Promise的链式操作

最简单的Promise例子

function timeout(ms){
     return new Promise(function(resolve){
         setTimeout(resolve, ms); 
     })
}
timeout(1000).then(function(){
     console.log("done");
})
Promise 和 回调 不同在于:
  • Promise简化了代码写法,有链式操作
  • 可以catch所有代理异步操作的错误,callback只能知道自己的错误
链式操作
简化了多层回调嵌套,避免“回调地狱 ”
所谓回调地狱,一层层嵌套,不利于阅读和维护:
setTimeout(function (name) {
  var catList = name + ',';
  setTimeout(function (name) {
    catList += name + ',';
    setTimeout(function (name) {
      catList += name + ',';
      setTimeout(function (name) {
        catList += name + ',';
        setTimeout(function (name) {
          catList += name;
          console.log(catList);
        }, 1, 'Lion');
      }, 1, 'Snow Leopard');
    }, 1, 'Lynx');
  }, 1, 'Jaguar');}, 1, 'Panther');

现在要一次执行p1、p2、p3、p4,用then函数,链式操作,

        p1().then(function () {
            console.log("我是回调");
            return p2();
        }).then(function () {
            console.log("我是回调");
            return p3();
        }).then(function () {
            console.log("我是回调");
            return p4();
        });

        var p1 = function(){
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    console.log('11111');
                    resolve("p1");
                }, 1000)
            })
        };
        function p2 () {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    console.log('22222');
                    resolve("p2")
                }, 1000)
            })
        }
        function p3 () {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    console.log('33333');
                    resolve("p3");
                }, 1000);
            })
        }
        function p4 () {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    console.log('44444');
                    resolve("p4");
                }, 1000);
            })
        }
原文地址:https://www.cnblogs.com/hjqbit/p/6883703.html