promise

使用promise

我们先可以了解一下$q的defer()方法创建的对象具有哪些方法

resolve(value):用来执行deferred promise,value可以为字符串,对象等。

reject(value):用来拒绝deferred promise,value可以为字符串,对象等。

notify(value):获取deferred promise的执行状态,然后使用这个函数来传递它。

then(successFunc, errorFunc, notifyFunc):无论promise是成功了还是失败了,当结果可用之后,then都会立刻异步调用successFunc,或者'errorFunc',在promise被执行或者拒绝之前,notifyFunc可能会被调用0到多次,以提供过程状态的提示。

catch(errorFunc):抛出异常的时候,触发该函数.可以为整个then链提供一个统一异常处理.

finally(callback):总是会被执行,不管 promise 被处理或者被拒绝,起清理作用 


1. 引用angular.js后,定义控制器,配置$q环境


2. 定义一个func函数.

function func() {

    var defer = $q.defer();//创建1个defer对象

    var promise = defer.promise;//获取promise对象


    promise.then(function (e) {

        console.log('then1-success' + e);

    }, function (e) {

        console.log('then1-faild' + e);

    }, function (e) {

        console.log('then1-notice' + e);

    }).then(function (e) {

        console.log('then2-success' + e);

        throw "then2 exception";

    }).catch(function (e) {

        console.log('catch' + e);

    }).finally(function (e) {

        console.log('finally' + e);

    });

    defer.notify('通知1');

    defer.notify('通知2');

    defer.resolve('成功1');

    defer.reject('失败1');

}

3. 触发func函数(绑定到scope上即可触发)


补充说明

在执行promise的resolve和reject方法时,表示异步结束.(所以此处没显示'失败1')

then2中,e为undefined.原因是上个then方法中并没有return对象.(同样只能在successFunc, errorFunc中返回才有效)

如果上个then方法返回一个promise对象,则then2会在promise异步结束时才触发,并获取到异步结果.


为了更好的说明,这里演示一下then返回promise的情况.

function funcPromise() {

    var defer = q.defer();

    var promise = defer.promise;

    promise.then(function() {

        var thenDefer = q.defer();

        timeout(function() {

            thenDefer.resolve('thenDefer 成功');

            //thenDefer.reject('thenDefer 失败');//会触发下个then的errorFunc

        });

        return thenDefer.promise;

    }).then(function(e) {

        console.log('then2-success' + e);

    },function(e) {

        console.log('then2-faild' + e);

    });

    defer.resolve();

}


$q.all

$q.all(),允许你等待并行的 promise 处理,当所有的 promise 都被处理结束之后,调用共同的回调

scope.all = function () {

    q.all([getAjaxPromise(), getTimePromise()]).then(function () {

        console.log(arguments);

    });

}

getAjaxPromise 和 getTimePromise 函数都返回promise对象了


$q.when

$q.when(),可以将非promise标准的对象 提供给then函数.

scope.when = function() {

    q.when('hello').then(function(e) {

        console.log(e);

    });


    q.when(getAjaxPromise()).then(function (e) {

        console.log(e);

    });

}

getAjaxPromise 是返回promise标准的 而'hello'是一个普通的字符

你可能感兴趣的:(promise)