zoukankan      html  css  js  c++  java
  • Bluebird-Core API(二)

    .error

    .error([function(any error) rejectedHandler]) -> Promise

    和catch一样,但是catch捕获了所有错误类型的异常,而error捕获是操作异常

    注:“errors”意为错误,作为对象能 够instanceof Error,不是字符串、数字等。See a string is not an error.

    下面例子跟.catch模式恒等的

    // Assumes OperationalError has been made global
    function isOperationalError(e) {
        if (e == null) return false;
        return (e instanceof OperationalError) || (e.isOperational === true);
    }
    
    // Now this bit:
    .catch(isOperationalError, function(e) {
        // ...
    })
    
    // Is equivalent to:
    
    .error(function(e) {
        // ...
    });

    For example, if a promisified function errbacks the node-style callback with an error, that could be caught with .error. However if the node-style callback throws an error, only .catch would catch that.

    In the following example you might want to handle just the SyntaxError from JSON.parse and Filesystem errors from fs but let programmer errors bubble as unhandled rejections:

    var fs = Promise.promisifyAll(require("fs"));
    
    fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) {
        console.log("Successful json")
    }).catch(SyntaxError, function (e) {
        console.error("file contains invalid json");
    }).error(function (e) {
        console.error("unable to read file, because: ", e.message);
    });

    Now, because there is no catch-all handler, if you typed console.lag (causes an error you don't expect), you will see:

    Possibly unhandled TypeError: Object #<Console> has no method 'lag'
        at application.js:8:13
    From previous event:
        at Object.<anonymous> (application.js:7:4)
        at Module._compile (module.js:449:26)
        at Object.Module._extensions..js (module.js:467:10)
        at Module.load (module.js:349:32)
        at Function.Module._load (module.js:305:12)
        at Function.Module.runMain (module.js:490:10)
        at startup (node.js:121:16)
        at node.js:761:3

    ( If you don't get the above - you need to enable long stack traces )

    And if the file contains invalid JSON:

    file contains invalid json

    And if the fs module causes an error like file not found:

    unable to read file, because:  ENOENT, open 'not_there.txt'

    .finally

    .finally(function() handler) -> Promise
    .lastly(function() handler) -> Promise

    传入一个句柄不管Promise结果如果都会执行,返回一个新的Promise,从.finally语义来说,这个句柄(handler)中最终值是不能修改的。

    Note: using .finally for resource management has better alternatives, see resource management

    Consider the example:

    function anyway() {
        $("#ajax-loader-animation").hide();
    }
    
    function ajaxGetAsync(url) {
        return new Promise(function (resolve, reject) {
            var xhr = new XMLHttpRequest;
            xhr.addEventListener("error", reject);
            xhr.addEventListener("load", resolve);
            xhr.open("GET", url);
            xhr.send(null);
        }).then(anyway, anyway);
    }

    This example doesn't work as intended because the then handler actually swallows the exception and returns undefinedfor any further chainers.

    The situation can be fixed with .finally:

    function ajaxGetAsync(url) {
        return new Promise(function (resolve, reject) {
            var xhr = new XMLHttpRequest;
            xhr.addEventListener("error", reject);
            xhr.addEventListener("load", resolve);
            xhr.open("GET", url);
            xhr.send(null);
        }).finally(function() {
            $("#ajax-loader-animation").hide();
        });
    }

    Now the animation is hidden but, unless it throws an exception, the function has no effect on the fulfilled or rejected value of the returned promise. This is similar to how the synchronous finally keyword behaves.

    If the handler function passed to .finally returns a promise, the promise returned by .finally will not be settled until the promise returned by the handler is settled. If the handler fulfills its promise, the returned promise will be fulfilled or rejected with the original value. If the handler rejects its promise, the returned promise will be rejected with the handler's value. This is similar to throwing an exception in a synchronous finally block, causing the original value or exception to be forgotten. This delay can be useful if the actions performed by the handler are done asynchronously. For example:

    function ajaxGetAsync(url) {
        return new Promise(function (resolve, reject) {
            var xhr = new XMLHttpRequest;
            xhr.addEventListener("error", reject);
            xhr.addEventListener("load", resolve);
            xhr.open("GET", url);
            xhr.send(null);
        }).finally(function() {
            return Promise.fromCallback(function(callback) {
                $("#ajax-loader-animation").fadeOut(1000, callback);
            });
        });
    }

    If the fade out completes successfully, the returned promise will be fulfilled or rejected with the value from xhr. If .fadeOutthrows an exception or passes an error to the callback, the returned promise will be rejected with the error from .fadeOut.

    For compatibility with earlier ECMAScript version, an alias .lastly is provided for .finally.

     

    .bind

    .bind(any|Promise<any> thisArg) -> BoundPromise
    Same as calling Promise.bind(thisArg, thisPromise).
  • 相关阅读:
    tgttg
    在OpenStack虚拟机实例中创建swap分区的一种方法
    产品:我想要的产品是网络存储+网络备份
    《哪来的天才?》读书笔记——天才源于练习,而且是针对性的练习
    一万小时理论的解读(神贴真开眼界:有意识的刻苦训练是必须的,要有精神动力,还必须有及时的反馈,对实力占优的活动比较有效;玩这样的活动是不行的)
    Cross-compiling Qt Embedded 5.5 for Raspberry Pi 2
    MSYS2的源配置
    关于iOS 5 Could not instantiate class named NSLayoutConstraint错误
    BAT线下战争:巨额投资或培养出自己最大对手(包括美团、58、饿了么在内的公司都在计划推出自己的支付工具和金融产品,腾讯只做2不做O)
    欢聚移动互联时代 在腾讯的夹缝中低调崛起
  • 原文地址:https://www.cnblogs.com/xiaopen/p/5618066.html
Copyright © 2011-2022 走看看