All files / libs/lang promiseExtra.js

100% Statements 0/0
100% Branches 0/0
100% Functions 0/0
100% Lines 0/0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47                                                                                             
/**
 * 扩展标准的 promise,包含下面两个方法
 *
 *   - Promise.prototype.finally
 *   - Promise.try
 *
 * @module      libs/lang/promiseExtra
 * @createdAt   2016-07-21
 *
 * @copyright   Copyright (c) 2016 Zhonglei Qiu
 * @license     Licensed under the MIT license.
 */
 
/**
 * Promise.prototype.finally
 *
 * @see {@link http://es6.ruanyifeng.com/#docs/promise#finally}
 */
/* istanbul ignore next */
if (!Promise.prototype.finally) {
  /* eslint-disable no-extend-native */
  Promise.prototype.finally = function(callback) {
    var P = this.constructor
    return this.then(
      function(value) { return P.resolve(callback()).then(function() { return value }) },
      function(reason) { return P.resolve(callback()).then(function() { throw reason }) }
    )
  }
  /* eslint-enable no-extend-native */
}
 
/**
 * Promise.try
 *
 * 来自:Bluebird
 *
 * @see [为什么要用它]{@link http://cryto.net/~joepie91/blog/2016/05/11/what-is-promise-try-and-why-does-it-matter/}
 */
/* istanbul ignore next */
if (!Promise.try) {
  Promise.try = function(fn) {
    return new Promise(function(resolve, reject) {
      resolve(fn())
    })
  }
}