本文介绍了棱角分明的$ q.reject()VS deferred.reject()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让角$ Q服务及其相关的对象和API的句柄。当我看到在我的控制台中的对象我看到:

I'm trying to get a handle on the angular $q service and its related objects and apis. When I look at the objects in my console I see:

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}

它提出了几个问题:

It raises a few questions:


  1. 有什么$ q.reject()和deferred.reject()之间的区别?当使用的呢?

  2. 什么是errorFn deferred.promise.then(successFn,errorFn)和catchFn deferred.promise.catch(catchFn)?之间的关系

  3. 如果我有一堆嵌套的承诺,并出现错误将最外层的捕捉()函数总是叫什么名字?如果还定义了什么是嵌套的承诺之一捕捉功能?请问该catch prevent从执行?
  4. 最外面抓

感谢。

推荐答案

1)$ q.reject是一个快捷方式创建一个延迟,然后立即拒绝;我经常用这个在errorFn如果我不能处理错误。

1) $q.reject is a shortcut to create a deferred and then reject it immediately; I often use this in an errorFn if I can't handle the error.

2)没什么,promise.catch(errorFn)是promise.then只是语法糖(NULL,errorFn),就像$ http服务的成功和错误的方法,所以你可以写code类的以下内容:

2) Nothing, promise.catch(errorFn) is just syntactic sugar for promise.then(null, errorFn), just like the success and error methods of the $http service, so you can write code like the following:

promise.
    then(function(result){
        // handle success
        return result;
    }, function errorHandler1(error){
        // handle error, exactly as if this was a separate catch in the chain.

    }).catch(function errorHandler2(error){
        // handle errors from errorHandler1
    });

3)这正是$ q.reject可以派上用场:

3) This is exactly where $q.reject can come in handy:

promise.
    catch(function(error){
       //Decide you can't handle the error
       return $q.reject(error); //This forwards the error to the next error handler;
    }).catch(function(error){
       // Here you may handle the error or reject it again.
       return 'An error occurred'; 
       //Now other errorFn in the promise chain won't be called, 
       // but the successFn calls will.
    }).catch(function(error){
       // This will never be called because the previous catch handles all errors.
    }).then(function(result){
       //This will always be called with either the result of promise if it was successful, or 
       //'An error occured' if it wasn't
    });

这篇关于棱角分明的$ q.reject()VS deferred.reject()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 13:37