promise 笔记

拒绝

var promise=new Promise(function(resolve,reject){

            throw new Error(0);

        });

        promise.then(function(arg){

            console.log(arg);

        }).catch(function(arg){

            console.log('c' + arg);//走这

        });

var promise=new Promise(function(resolve,reject){

            reject(0);

        });

        promise.then(function(arg){

            console.log(arg);

        },function(arg){

            console.log('j' + arg);//走这

        }).catch(function(arg){

            console.log('c' + arg);

异常

var promise=new Promise(function(resolve,reject){

            throw new Error(0);

        });

        promise.then(function(arg){

            console.log(arg);

        }).catch(function(arg){

            console.log('c' + arg);//走这

        });

var promise=new Promise(function(resolve,reject){

            reject(0);

        });

        promise.then(function(arg){

            console.log(arg);

        },function(arg){

            console.log('j' + arg);//走这

        }).catch(function(arg){

            console.log('c' + arg);

then() cath()会构建和返回一个promise实例

var promise=new Promise(function(resolve,reject){

            throw new Error('x');

        });

        promise.then(function(arg){

            console.log(arg);

            return 'xx';//返回给下一个thenresolve(抛异常也是下一个thenresolve

        },function(arg){

            console.log('reject' + arg);

            return 'xx';//返回给下一个thenreject

        }).catch(function(arg){

            console.log('cathc' + arg);

        })

        .then(function(data){

            console.log('last resolve:' + data);

        },function(data){

            console.log('last reject:' + data);

        });

延迟,异步异常

var promise = new Promise(function(resolve, reject) {

            setTimeout(function() {

                reject('x');//可以捕获,如果是 throw 一个error就无法捕获

            });

        });

        promise.then(function(arg) {

                console.log('resole:' + arg);

            }, function(arg) {

                console.log('reject' + arg);

            })

            .catch(function(arg) {

                console.log('cathc:' + arg);

            })

补充:

window.addEventListener("unhandledrejection", function (event) {

  console.warn("WARNING: Unhandled promise rejection. Shame on you! Reason: "

               + event.reason);});

用来捕获拒绝,window.onerror只是捕获异常不会捕获promise的拒绝

posted @ 2017-03-29 23:09  世上最帅的程序员  阅读(273)  评论(0编辑  收藏  举报