• Javascript Promise对象学习


    ES6中的Promise对象

    var p = new Promise(function(resolve, reject){
        window.setTimeout(function(){
            console.log("1",1);
            resolve(1);
        },10);
    });
    p.then(function(a){
        return new Promise(function(resolve,reject){
            window.setTimeout(function(){
                console.log("2",a+1);
                resolve(a + 1);
            },10);
        });
    }).then(function(a){
        return new Promise(function(resolve,reject){
            window.setTimeout(function(){
                console.log("3",a+1);
                resolve(a + 1);
            },10);
        });
    }).then((a)=>new Promise((resolve,reject)=>{
        window.setTimeout(function(){
            console.log("52222",a+1);
            resolve(a + 1);
        },10);
    }));
    

      

    for循环中的ajax请求依次执行,而不是无序执行。

    (function () {
    
    
        var ajax = function(callback){
            window.setTimeout(function(){
                callback(new Date());
            },1000);
        };
    
        var promiseAjax = function(num){
            return function (pre){
                return new Promise(function (resolve, reject) {
                    ajax(function (d) {
                        console.log(num,d);
                        resolve(d);
                    });
                });
            }
        } ;
    
    
    
        var p = promiseAjax(-1)();
        for (var i = 0; i < 10; i++) {
            p = p.then(promiseAjax(i));
        }
    
    
    })();
    

      

    Angular中的$q对象

        var $q = {};
        var deferred = $q.defer();
        var promise = deferred.promise;
        promise.then(function(a){
            return a + "222"
        }).then(function(a){
            var deferred = $q.defer();
            window.setTimeout(function(){
                deferred.resolve("333");
            },100);
            return deferred.promise;
        });
        deferred.resolve("1111");
    

      

    var deferred = $q.defer()
    
    ...(and then from console inspection)...
    
    $q: Object {defer: function, reject: function, when: function, all: function}
    
    deferred: Object {resolve: function, reject: function, notify: function, promise: Object}
    
    deferred.promise: Object {then: function, catch: function, finally: function}
    
    $q.reject(reason) returns a rejected promise with the reason passed as argument and defered. Reject rejects an existent defered whether its process has finished or not.
    

      

    try、catch、throw和then、catch、reject

  • 相关阅读:
    codeforces 466D
    codeforces 360B
    codeforces 383D
    codeforces 679B
    codeforces 571B
    codeforces 494B
    CodeForces 660D Number of Parallelograms(n个点所能组成的最多平行四边形数量)
    算法竞赛模板 最短路
    算法竞赛模板 string中substr函数的运用
    HDOJ 1269 迷宫城堡(tarjan模板题)
  • 原文地址:https://www.cnblogs.com/lhp2012/p/5246881.html
Copyright © 2020-2023  润新知