zoukankan      html  css  js  c++  java
  • 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);
                })
            }
  • 相关阅读:
    springboot之mybatis别名的设置
    webstorm
    万字长文把 VSCode 打造成 C++ 开发利器
    残差residual VS 误差 error
    参数与非参数的机器学习算法
    阿里云产品梳理
    aws产品整理
    Azure产品整理
    OpenStack产品摘要
    头条、美团、滴滴、阿里、腾讯、百度、华为、京东职级体系及对应薪酬
  • 原文地址:https://www.cnblogs.com/hjqbit/p/6883703.html
Copyright © 2011-2022 走看看