promise-toolbox
Advanced tools
Comparing version 0.8.0 to 0.8.1
@@ -1,2 +0,917 @@ | ||
'use strict';Object.defineProperty(exports,'__esModule',{value:!0});exports.TimeoutError=exports.promisifyAll=exports.promisify=exports.finally=exports.fromCallback=exports.forOwn=exports.forIterable=exports.forIn=exports.forEach=exports.forArray=exports.makeAsyncIterator=exports.defer=exports.cancelable=exports.cancellable=exports.CancelToken=exports.Cancel=exports.nodeify=exports.isPromise=void 0;var _typeof='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&'function'==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj};var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();exports.all=all;exports.asCallback=asCallback;exports.catchPlus=catchPlus;exports.delay=delay;exports.join=join;exports.lastly=lastly;exports.reflect=reflect;exports.settle=settle;exports.some=some;exports.tap=tap;exports.timeout=timeout;exports.unpromisify=unpromisify;var _makeError=require('make-error');function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return call&&('object'==typeof call||'function'==typeof call)?call:self}function _inherits(subClass,superClass){if('function'!=typeof superClass&&null!==superClass)throw new TypeError('Super expression must either be null or a function, not '+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}if('function'!=typeof Promise||'function'!=typeof Promise.reject||'function'!=typeof Promise.resolve)throw new Error('a standard Promise implementation is required (https://github.com/JsCommunity/promise-toolbox#usage)');var _endsWith=function _endsWith(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:a.length;return c-=b.length,0<=c&&a.indexOf(b,c)===c},_isArray=Array.isArray||function(a){return a instanceof Array},_isLength=function _isLength(a){return'number'==typeof a&&0<=a&&a<Infinity&&Math.floor(a)===a},_isArrayLike=function _isArrayLike(a){return a&&'function'!=typeof a&&_isLength(a.length)},_iteratorSymbol='function'==typeof Symbol&&Symbol.iterator||'@@iterator',_isIterable=function _isIterable(a){return a&&'function'==typeof a[_iteratorSymbol]},_noop=function _noop(){},_forArray=function _forArray(a,b){var c=a.length;for(var d=0;d<c;++d)b(a[d],d,a)},_forIn=function _forIn(a,b){for(var c in a)b(a[c],c,a)},_forIterable=function _forIterable(a,b){for(var c=a[Symbol.iterator](),d=void 0;!(d=c.next()).done;)b(d.value,null,a)},hasOwnProperty=Object.prototype.hasOwnProperty,_forOwn=function _forOwn(a,b){for(var c in a)hasOwnProperty.call(a,c)&&b(a[c],c,a)},_forEach=function _forEach(a,b){return _isArray(a)?_forArray(a,b):_isIterable(a)?_forIterable(a,b):_isArrayLike(a)?_forArray(a,b):_forOwn(a,b)},_map=function _map(a,b){var c=_isArrayLike(a)?Array(a.length):{};return b&&_forEach(a,function(d,e){c[e]=b(d,e,a)}),c};var isPromise=exports.isPromise=function isPromise(a){return null!=a&&'function'==typeof a.then};var _makeAsyncIterator=function _makeAsyncIterator(a){return function(b,c){var d=Promise.resolve();return a(b,function(e,g){d=isPromise(e)?d.then(function(){return e.then(function(h){return c(h,g,b)})}):d.then(function(){return c(e,g,b)})}),d}},_wrap=function _wrap(a){return isPromise(a)?a:Promise.resolve(a)},_wrapCall=function _wrapCall(a,b,c){try{return _wrap(a.apply(c,b))}catch(d){return Promise.reject(d)}},_all=function _all(a,b){return new Promise(function(c,d){var e=_map(a,b),g=1,h=function h(){if(0==--g){var l=e;e=null,c(l)}},j=function j(l,m){e&&(e[m]=l,h())},k=function k(l){e&&(e=null,d(l))};_forEach(b?e:a,function(l,m){++g,isPromise(l)?l.then(function(o){return j(o,m)},k):j(l,m)}),h()})};function all(a){return _wrap(this).then(function(b){return _all(b,a)})}function asCallback(a){return a&&this.then(function(b){return a(null,b)},function(b){return a(b)}).then(null,_noop),this}exports.nodeify=asCallback;var Cancel=exports.Cancel=function(){function Cancel(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:'this action has been canceled';_classCallCheck(this,Cancel),Object.defineProperty(this,'message',{enumerable:!0,value:a})}return _createClass(Cancel,[{key:'toString',value:function toString(){return'Cancel: '+this._message}}]),Cancel}();var _cancelTokenTag='CancelToken',_toStringTagSymbol='function'==typeof Symbol&&Symbol.toStringTag||'@@toStringTag';var CancelToken=exports.CancelToken=function(){function CancelToken(a){var _this=this;_classCallCheck(this,CancelToken),this._cancel=null,this._promise=null,this._resolve=null;var _b=function b(c){_b=_noop;var d=_this._cancel=new Cancel(c),e=_this._resolve;e&&(e(d),_this._resolve=null)};a(function(c){return _b(c)})}return _createClass(CancelToken,null,[{key:'isCancelToken',value:function isCancelToken(a){return null!=a&&'function'==typeof a[_toStringTagSymbol]&&a[_toStringTagSymbol]()===_cancelTokenTag}},{key:'source',value:function source(){var a=void 0,b=new CancelToken(function(c){a=c});return{cancel:a,token:b}}}]),_createClass(CancelToken,[{key:'throwIfRequested',value:function throwIfRequested(){var a=this._cancel;if(a)throw a}},{key:_toStringTagSymbol,value:function value(){return _cancelTokenTag}},{key:'promise',get:function get(){var _this2=this,a=this._promise;if(!a){var b=this._cancel;a=b?this._promise=Promise.resolve(b):this._promise=new Promise(function(c){_this2._resolve=c})}return a}},{key:'requested',get:function get(){return!!this._cancel}}]),CancelToken}();var cancellable=exports.cancellable=function cancellable(a,b,c){function d(){var g=arguments.length;if(g&&arguments[0]instanceof CancelToken)return e.apply(this,k);var _CancelToken$source=CancelToken.source(),h=_CancelToken$source.cancel,j=_CancelToken$source.token,k=Array(g+1);k[0]=j;for(var m=0;m<g;++m)k[m+1]=arguments[m];var l=e.apply(this,k);return l.cancel=h,l}var e=c?c.value:a;return c?(c.value=d,c):d};exports.cancelable=cancellable;var _isOperationalError=function _isOperationalError(a){return!(a instanceof ReferenceError||a instanceof SyntaxError||a instanceof TypeError)},_errorWrapper={error:null},_tryCatch=function _tryCatch(a){try{return a()}catch(b){return _errorWrapper.error=b,_errorWrapper}},_matchError=function _matchError(a,b){return'function'==typeof a?a.prototype instanceof Error?b instanceof a:a(b):'object'==('undefined'==typeof a?'undefined':_typeof(a))?null!=b&&_tryCatch(function(){return _forOwn(a,function(c,d){if(b[d]!==c)throw null})})!==_errorWrapper:void 0};function catchPlus(){var _this3=this,a=arguments.length-1,b=void 0;if(0>a||'function'!=typeof(b=arguments[a]))return this;var c=void 0;if(a){c=Array(a);for(var d=0;d<a;++d)c[d]=arguments[d]}return _wrap(this).then(null,function(d){if(c){for(var _e=0;_e<a;++_e)if(_matchError(c[_e],d))return b(d);}else if(_isOperationalError(d))return b(d);return _this3})}var defer=exports.defer=function defer(){var a=void 0,b=void 0,c=new Promise(function(d,e){a=d,b=e});return{promise:c,reject:b,resolve:a}};function delay(a){var _this4=this;return isPromise(this)?this.then(function(b){return new Promise(function(c){setTimeout(function(){return c(b)},a)})}):new Promise(function(b){setTimeout(function(){return b(_this4)},a)})}var makeAsyncIterator=exports.makeAsyncIterator=function makeAsyncIterator(a){var b=_makeAsyncIterator(a);return function(c){return _wrap(this).then(function(d){return b(d,c)}).then(_noop)}};var forArray=exports.forArray=makeAsyncIterator(_forArray);var forEach=exports.forEach=makeAsyncIterator(_forEach);var forIn=exports.forIn=makeAsyncIterator(_forIn);var forIterable=exports.forIterable=makeAsyncIterator(_forIterable);var forOwn=exports.forOwn=makeAsyncIterator(_forOwn);var fromCallback=exports.fromCallback=function fromCallback(a){return new Promise(function(b,c){a(function(d,e){return d?c(d):b(e)})})};function join(){var a=arguments.length-1,b=arguments[a],c=void 0;if(0==a)return new Promise(function(d){return d(b())});if(1!=a){c=Array(a);for(var d=0;d<a;++d)c[d]=arguments[d]}else if(!_isArrayLike(c=arguments[0]))return _wrap(c).then(function(d){return b(d)});return _all(c).then(function(d){return b.apply(null,d)})}function lastly(a){var _this5=this;return _wrap(this).then(function(){return _wrap(a()).then(function(){return _this5})},function(){return _wrap(a()).then(function(){return _this5})})}exports.finally=lastly;var _setFunctionNameAndLength=function(){var a=Object.defineProperties;try{var b=a(function(){},{length:{value:2},name:{value:'foo'}});if(2===b.length&&'foo'===b.name)return function(c,d,e){return a(c,{length:{configurable:!0,value:e},name:{configurable:!0,value:d}})}}catch(b){}return function(b){return b}}();var promisify=exports.promisify=function promisify(a,b){return _setFunctionNameAndLength(function(){var _this6=this,c=arguments.length,d=Array(c+1);for(var e=0;e<c;++e)d[e]=arguments[e];return new Promise(function(e,g){d[c]=function(h,j){return h?g(h):e(j)},a.apply(b||_this6,d)})},a.name,a.length&&a.length-1)};var _DEFAULT_PALL_MAPPER=function _DEFAULT_PALL_MAPPER(a){return!(_endsWith(a,'Sync')||_endsWith(a,'Async'))&&a};var promisifyAll=exports.promisifyAll=function promisifyAll(a){var _ref=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},_ref$mapper=_ref.mapper,b=void 0===_ref$mapper?_DEFAULT_PALL_MAPPER:_ref$mapper,_ref$target=_ref.target,c=void 0===_ref$target?{}:_ref$target,_ref$context=_ref.context,d=void 0===_ref$context?a:_ref$context;return _forIn(a,function(e,g){var h=void 0;'function'==typeof e&&(h=b(g,e,a))&&(c[h]=promisify(e,d))}),c};var FN_FALSE=function FN_FALSE(){return!1},FN_TRUE=function FN_TRUE(){return!0},_reflectResolution=function(a){return function(b){return{__proto__:a,value:function value(){return b}}}}({isFulfilled:FN_TRUE,isPending:FN_FALSE,isRejected:FN_FALSE,isResolved:FN_TRUE,reason:function reason(){throw new Error('no reason, the promise has resolved')}}),_reflectRejection=function(a){return function(b){return{__proto__:a,reason:function reason(){return b}}}}({isFulfilled:FN_FALSE,isPending:FN_FALSE,isRejected:FN_TRUE,isResolved:FN_FALSE,value:function value(){throw new Error('no value, the promise has rejected')}});function reflect(){return _wrap(this).then(_reflectResolution,_reflectRejection)}function settle(){return all.call(this,function(a){return reflect.call(a)})}var _some=function _some(a,b){return new Promise(function(c,d){var e=[],g=[],h=function h(l){e&&(e.push(l),0==--b&&(c(e),e=g=null))},j=-b,k=function k(l){e&&(g.push(l),0==--j&&(d(g),e=g=null))};_forEach(a,function(l){++j,_wrap(l).then(h,k)})})};function some(a){return _wrap(this).then(function(b){return _some(b,a)})}function tap(a,b){var _this7=this,c=function c(){return _this7};return _wrap(this).then(a&&function(d){return _wrap(a(d)).then(c)},b&&function(d){return _wrap(b(d)).then(c)})}var TimeoutError=exports.TimeoutError=function(_BaseError){function TimeoutError(){return _classCallCheck(this,TimeoutError),_possibleConstructorReturn(this,(TimeoutError.__proto__||Object.getPrototypeOf(TimeoutError)).call(this,'operation timed out'))}return _inherits(TimeoutError,_BaseError),TimeoutError}(_makeError.BaseError);function timeout(a,b){var _this9=this;return new Promise(function(c,d){var e=setTimeout(function(){if(e=null,'function'==typeof _this9.cancel&&_this9.cancel(),b)try{c(b())}catch(g){d(g)}else d(new TimeoutError)},a);_wrap(_this9).then(function(g){null!==e&&clearTimeout(e),c(g)},function(g){null!==e&&clearTimeout(e),d(g)})})}function unpromisify(){var a=this;return _setFunctionNameAndLength(function(){var b=arguments.length-1,c=void 0;if(0>b||'function'!=typeof(c=arguments[b]))throw new Error('missing callback');var d=Array(b);for(var e=0;e<b;++e)d[e]=arguments[e];_wrapCall(a,d,this).then(function(e){return c(null,e)},function(e){return c(e)})},a.name,a.length+1)} | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.TimeoutError = exports.promisifyAll = exports.promisify = exports.finally = exports.fromCallback = exports.forOwn = exports.forIterable = exports.forIn = exports.forEach = exports.forArray = exports.makeAsyncIterator = exports.defer = exports.cancelable = exports.cancellable = exports.CancelToken = exports.Cancel = exports.nodeify = exports.isPromise = undefined; | ||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
exports.all = all; | ||
exports.asCallback = asCallback; | ||
exports.catchPlus = catchPlus; | ||
exports.delay = delay; | ||
exports.join = join; | ||
exports.lastly = lastly; | ||
exports.reflect = reflect; | ||
exports.settle = settle; | ||
exports.some = some; | ||
exports.tap = tap; | ||
exports.timeout = timeout; | ||
exports.unpromisify = unpromisify; | ||
var _makeError = require('make-error'); | ||
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } | ||
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
// =================================================================== | ||
if (typeof Promise !== 'function' || typeof Promise.reject !== 'function' || typeof Promise.resolve !== 'function') { | ||
throw new Error('a standard Promise implementation is required (https://github.com/JsCommunity/promise-toolbox#usage)'); | ||
} | ||
// =================================================================== | ||
var _endsWith = function _endsWith(str, suffix) { | ||
var pos = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : str.length; | ||
pos -= suffix.length; | ||
return pos >= 0 && str.indexOf(suffix, pos) === pos; | ||
}; | ||
var _isArray = Array.isArray || function (value) { | ||
return value instanceof Array; | ||
}; | ||
var _isLength = function _isLength(value) { | ||
return typeof value === 'number' && value >= 0 && value < Infinity && Math.floor(value) === value; | ||
}; | ||
var _isArrayLike = function _isArrayLike(value) { | ||
return value && typeof value !== 'function' && _isLength(value.length); | ||
}; | ||
var _iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator || '@@iterator'; | ||
var _isIterable = function _isIterable(value) { | ||
return value && typeof value[_iteratorSymbol] === 'function'; | ||
}; | ||
var _noop = function _noop() {}; | ||
// ------------------------------------------------------------------- | ||
var _forArray = function _forArray(array, iteratee) { | ||
var length = array.length; | ||
for (var i = 0; i < length; ++i) { | ||
iteratee(array[i], i, array); | ||
} | ||
}; | ||
var _forIn = function _forIn(object, iteratee) { | ||
for (var key in object) { | ||
iteratee(object[key], key, object); | ||
} | ||
}; | ||
var _forIterable = function _forIterable(iterable, iteratee) { | ||
var iterator = iterable[Symbol.iterator](); | ||
var current = void 0; | ||
while (!(current = iterator.next()).done) { | ||
iteratee(current.value, null, iterable); | ||
} | ||
}; | ||
var hasOwnProperty = Object.prototype.hasOwnProperty; | ||
var _forOwn = function _forOwn(object, iteratee) { | ||
for (var key in object) { | ||
if (hasOwnProperty.call(object, key)) { | ||
iteratee(object[key], key, object); | ||
} | ||
} | ||
}; | ||
var _forEach = function _forEach(collection, iteratee) { | ||
return _isArray(collection) ? _forArray(collection, iteratee) : _isIterable(collection) ? _forIterable(collection, iteratee) : _isArrayLike(collection) ? _forArray(collection, iteratee) : _forOwn(collection, iteratee); | ||
}; | ||
var _map = function _map(collection, iteratee) { | ||
var result = _isArrayLike(collection) ? new Array(collection.length) : {}; | ||
// If iteratee is not a function, simply returns the new container. | ||
if (iteratee) { | ||
_forEach(collection, function (item, key) { | ||
result[key] = iteratee(item, key, collection); | ||
}); | ||
} | ||
return result; | ||
}; | ||
// =================================================================== | ||
var isPromise = exports.isPromise = function isPromise(value) { | ||
return value != null && typeof value.then === 'function'; | ||
}; | ||
// ------------------------------------------------------------------- | ||
var _makeAsyncIterator = function _makeAsyncIterator(iterator) { | ||
return function (promises, cb) { | ||
var mainPromise = Promise.resolve(); | ||
iterator(promises, function (promise, key) { | ||
mainPromise = isPromise(promise) ? mainPromise.then(function () { | ||
return promise.then(function (value) { | ||
return cb(value, key, promises); | ||
}); | ||
}) : mainPromise.then(function () { | ||
return cb(promise, key, promises); | ||
}); | ||
}); | ||
return mainPromise; | ||
}; | ||
}; | ||
var _wrap = function _wrap(value) { | ||
return isPromise(value) ? value : Promise.resolve(value); | ||
}; | ||
var _wrapCall = function _wrapCall(fn, args, thisArg) { | ||
try { | ||
return _wrap(fn.apply(thisArg, args)); | ||
} catch (error) { | ||
return Promise.reject(error); | ||
} | ||
}; | ||
// =================================================================== | ||
var _all = function _all(promises, mapFn) { | ||
return new Promise(function (resolve, reject) { | ||
// mapFn may be undefined but it's okay :) | ||
var result = _map(promises, mapFn); | ||
var count = 1; | ||
var onFulfillment0 = function onFulfillment0() { | ||
if (--count === 0) { | ||
var tmp = result; | ||
result = null; | ||
resolve(tmp); | ||
} | ||
}; | ||
var onFulfillment = function onFulfillment(value, key) { | ||
if (!result) { | ||
return; | ||
} | ||
result[key] = value; | ||
onFulfillment0(); | ||
}; | ||
var onRejection = function onRejection(reason) { | ||
if (!result) { | ||
return; | ||
} | ||
result = null; | ||
reject(reason); | ||
}; | ||
_forEach(mapFn ? result : promises, function (promise, key) { | ||
++count; | ||
if (isPromise(promise)) { | ||
promise.then(function (value) { | ||
return onFulfillment(value, key); | ||
}, onRejection); | ||
} else { | ||
onFulfillment(promise, key); | ||
} | ||
}); | ||
onFulfillment0(); | ||
}); | ||
}; | ||
// Returns a promise which resolves when all the promises in a | ||
// collection have resolved or rejects with the reason of the first | ||
// promise that rejects. | ||
// | ||
// Optionally a function can be provided to map all items in the | ||
// collection before waiting for completion. | ||
// | ||
// Usage: promises::all([ mapFn ]) | ||
function all(mapFn) { | ||
return _wrap(this).then(function (promises) { | ||
return _all(promises, mapFn); | ||
}); | ||
} | ||
// ------------------------------------------------------------------- | ||
// Usage: promise::asCallback(cb) | ||
function asCallback(cb) { | ||
// cb can be undefined. | ||
if (cb) { | ||
this.then(function (value) { | ||
return cb(null, value); | ||
}, function (error) { | ||
return cb(error); | ||
}).then(null, _noop); | ||
} | ||
return this; | ||
} | ||
exports.nodeify = asCallback; | ||
// ------------------------------------------------------------------- | ||
var Cancel = exports.Cancel = function () { | ||
function Cancel() { | ||
var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'this action has been canceled'; | ||
_classCallCheck(this, Cancel); | ||
Object.defineProperty(this, 'message', { | ||
enumerable: true, | ||
value: message | ||
}); | ||
} | ||
_createClass(Cancel, [{ | ||
key: 'toString', | ||
value: function toString() { | ||
return `Cancel: ${this._message}`; | ||
} | ||
}]); | ||
return Cancel; | ||
}(); | ||
var _cancelTokenTag = 'CancelToken'; | ||
var _toStringTagSymbol = typeof Symbol === 'function' && Symbol.toStringTag || '@@toStringTag'; | ||
// https://github.com/zenparsing/es-cancel-token | ||
// https://tc39.github.io/proposal-cancelable-promises/ | ||
var CancelToken = exports.CancelToken = function () { | ||
_createClass(CancelToken, null, [{ | ||
key: 'isCancelToken', | ||
value: function isCancelToken(value) { | ||
return value != null && typeof value[_toStringTagSymbol] === 'function' && value[_toStringTagSymbol]() === _cancelTokenTag; | ||
} | ||
// https://github.com/zenparsing/es-cancel-token/issues/3#issuecomment-221173214 | ||
}, { | ||
key: 'source', | ||
value: function source() { | ||
var cancel = void 0; | ||
var token = new CancelToken(function (cancel_) { | ||
cancel = cancel_; | ||
}); | ||
return { cancel, token }; | ||
} | ||
}, { | ||
key: 'race', | ||
value: function race(tokens) { | ||
var _CancelToken$source = CancelToken.source(), | ||
cancel = _CancelToken$source.cancel, | ||
token = _CancelToken$source.token; | ||
_forEach(tokens, function (token) { | ||
var reason = token.reason; | ||
if (reason) { | ||
cancel(reason); | ||
return false; | ||
} | ||
(token._listeners || (token._listeners = [])).push(cancel); | ||
}); | ||
return token; | ||
} | ||
}]); | ||
function CancelToken(executor) { | ||
var _this = this; | ||
_classCallCheck(this, CancelToken); | ||
this._listeners = null; | ||
this._promise = null; | ||
this._reason = undefined; | ||
this._resolve = null; | ||
var _cancelOnce = function cancelOnce(message) { | ||
_cancelOnce = _noop; | ||
var reason = _this._reason = message instanceof Cancel ? message : new Cancel(message); | ||
var resolve = _this._resolve; | ||
if (resolve) { | ||
_this._resolve = null; | ||
resolve(reason); | ||
} | ||
// notify sync listeners (for race) | ||
var listeners = _this._listeners; | ||
if (listeners) { | ||
_this._listeners = null; | ||
_forArray(listeners, function (listener) { | ||
return void listener(reason); | ||
}); | ||
} | ||
}; | ||
var cancel = function cancel(message) { | ||
return _cancelOnce(message); | ||
}; | ||
executor(cancel); | ||
} | ||
_createClass(CancelToken, [{ | ||
key: 'throwIfRequested', | ||
value: function throwIfRequested() { | ||
var cancel = this._reason; | ||
if (cancel) { | ||
throw cancel; | ||
} | ||
} | ||
}, { | ||
key: _toStringTagSymbol, | ||
value: function value() { | ||
return _cancelTokenTag; | ||
} | ||
}, { | ||
key: 'promise', | ||
get: function get() { | ||
var _this2 = this; | ||
var promise = this._promise; | ||
if (!promise) { | ||
var reason = this._reason; | ||
promise = this._promise = reason ? Promise.resolve(reason) : new Promise(function (resolve) { | ||
_this2._resolve = resolve; | ||
}); | ||
} | ||
return promise; | ||
} | ||
}, { | ||
key: 'reason', | ||
get: function get() { | ||
return this._reason; | ||
} | ||
}, { | ||
key: 'requested', | ||
get: function get() { | ||
return this._reason !== undefined; | ||
} | ||
}]); | ||
return CancelToken; | ||
}(); | ||
// Usage: | ||
// | ||
// @cancellable | ||
// async fn (cancelToken, other, args) { | ||
// if (!cancelToken.requested) { | ||
// doStuff() | ||
// } | ||
// | ||
// cancelToken.throwIfRequested() | ||
// | ||
// doSomeMoreStuff() | ||
// | ||
// cancelToken.promise.then(() => { | ||
// // Do stuff if canceled. | ||
// }) | ||
// | ||
// // do other stuff. | ||
// } | ||
var cancellable = exports.cancellable = function cancellable(target, name, descriptor) { | ||
var fn = descriptor ? descriptor.value : target; | ||
function cancellableWrapper() { | ||
var length = arguments.length; | ||
if (length && CancelToken.isCancelToken(arguments[0])) { | ||
return fn.apply(this, arguments); | ||
} | ||
var _CancelToken$source2 = CancelToken.source(), | ||
cancel = _CancelToken$source2.cancel, | ||
token = _CancelToken$source2.token; | ||
var args = new Array(length + 1); | ||
args[0] = token; | ||
for (var i = 0; i < length; ++i) { | ||
args[i + 1] = arguments[i]; | ||
} | ||
var promise = fn.apply(this, args); | ||
promise.cancel = cancel; | ||
return promise; | ||
} | ||
if (descriptor) { | ||
descriptor.value = cancellableWrapper; | ||
return descriptor; | ||
} | ||
return cancellableWrapper; | ||
}; | ||
exports.cancelable = cancellable; // alternative US spelling | ||
// ------------------------------------------------------------------- | ||
var _isOperationalError = function _isOperationalError(reason) { | ||
return !(reason instanceof ReferenceError || reason instanceof SyntaxError || reason instanceof TypeError); | ||
}; | ||
// See: https://github.com/petkaantonov/bluebird/blob/d8907d15f0a1997a5d3c0526cd4da5ba1b135cfa/src/util.js#L7-L30 | ||
var _errorWrapper = { error: null }; | ||
var _tryCatch = function _tryCatch(fn) { | ||
try { | ||
return fn(); | ||
} catch (error) { | ||
_errorWrapper.error = error; | ||
return _errorWrapper; | ||
} | ||
}; | ||
var _matchError = function _matchError(predicate, error) { | ||
if (typeof predicate === 'function') { | ||
return predicate.prototype instanceof Error ? error instanceof predicate : predicate(error); | ||
} | ||
if (typeof predicate === 'object') { | ||
return error != null && _tryCatch(function () { | ||
return _forOwn(predicate, function (value, prop) { | ||
if (error[prop] !== value) { | ||
throw null; // eslint-disable-line no-throw-literal | ||
} | ||
}); | ||
}) !== _errorWrapper; | ||
} | ||
}; | ||
// Similar to `Promise#catch()` but: | ||
// - support predicates | ||
// - do not catch `ReferenceError`, `SyntaxError` or `TypeError` | ||
// unless they match a predicate because they are usually programmer | ||
// errors and should be handled separately. | ||
function catchPlus() { | ||
var _this3 = this; | ||
var n = arguments.length - 1; | ||
var cb = void 0; | ||
if (n < 0 || typeof (cb = arguments[n]) !== 'function') { | ||
return this; | ||
} | ||
var predicates = void 0; | ||
if (n) { | ||
predicates = new Array(n); | ||
for (var i = 0; i < n; ++i) { | ||
predicates[i] = arguments[i]; | ||
} | ||
} | ||
return _wrap(this).then(null, function (reason) { | ||
if (predicates) { | ||
for (var _i = 0; _i < n; ++_i) { | ||
if (_matchError(predicates[_i], reason)) { | ||
return cb(reason); | ||
} | ||
} | ||
} else if (_isOperationalError(reason)) { | ||
return cb(reason); | ||
} | ||
// Forward error without throwing (perf). | ||
return _this3; | ||
}); | ||
} | ||
// ------------------------------------------------------------------- | ||
// Discouraged but sometimes necessary way to create a promise. | ||
var defer = exports.defer = function defer() { | ||
var resolve = void 0, | ||
reject = void 0; | ||
var promise = new Promise(function (resolve_, reject_) { | ||
// eslint-disable-line promise/param-names | ||
resolve = resolve_; | ||
reject = reject_; | ||
}); | ||
return { | ||
promise, | ||
reject, | ||
resolve | ||
}; | ||
}; | ||
// ------------------------------------------------------------------- | ||
// Usage: promise::delay(ms) | ||
function delay(ms) { | ||
var _this4 = this; | ||
return isPromise(this) ? this.then(function (value) { | ||
return new Promise(function (resolve) { | ||
setTimeout(function () { | ||
return resolve(value); | ||
}, ms); | ||
}); | ||
}) : new Promise(function (resolve) { | ||
setTimeout(function () { | ||
return resolve(_this4); | ||
}, ms); | ||
}); | ||
} | ||
// ------------------------------------------------------------------- | ||
var makeAsyncIterator = exports.makeAsyncIterator = function makeAsyncIterator(iterator) { | ||
var asyncIterator = _makeAsyncIterator(iterator); | ||
return function (cb) { | ||
return _wrap(this).then(function (promises) { | ||
return asyncIterator(promises, cb); | ||
}).then(_noop); // Resolves to undefined | ||
}; | ||
}; | ||
var forArray = exports.forArray = makeAsyncIterator(_forArray); | ||
var forEach = exports.forEach = makeAsyncIterator(_forEach); | ||
var forIn = exports.forIn = makeAsyncIterator(_forIn); | ||
var forIterable = exports.forIterable = makeAsyncIterator(_forIterable); | ||
var forOwn = exports.forOwn = makeAsyncIterator(_forOwn); | ||
// ------------------------------------------------------------------- | ||
// Usage: | ||
// | ||
// fromCallback(cb => fs.readFile('foo.txt', cb)) | ||
// .then(content => { | ||
// console.log(content) | ||
// }) | ||
var fromCallback = exports.fromCallback = function fromCallback(fn) { | ||
return new Promise(function (resolve, reject) { | ||
fn(function (error, result) { | ||
return error ? reject(error) : resolve(result); | ||
}); | ||
}); | ||
}; | ||
// ------------------------------------------------------------------- | ||
// Usage: join(p1, ..., pn, cb) or join([p1, ..., pn], cb) | ||
function join() { | ||
var n = arguments.length - 1; | ||
var cb = arguments[n]; | ||
var promises = void 0; | ||
if (n === 0) { | ||
return new Promise(function (resolve) { | ||
return resolve(cb()); | ||
}); | ||
} else if (n !== 1) { | ||
promises = new Array(n); | ||
for (var i = 0; i < n; ++i) { | ||
promises[i] = arguments[i]; | ||
} | ||
} else if (!_isArrayLike(promises = arguments[0])) { | ||
return _wrap(promises).then(function (value) { | ||
return cb(value); | ||
}); | ||
} | ||
return _all(promises).then(function (args) { | ||
return cb.apply(null, args); | ||
}); | ||
} | ||
// ------------------------------------------------------------------- | ||
// Ponyfill for Promise.finally(cb) | ||
// | ||
// Usage: promise::lastly(cb) | ||
function lastly(cb) { | ||
var _this5 = this; | ||
return _wrap(this).then(function (value) { | ||
return _wrap(cb()).then(function () { | ||
return _this5; | ||
}); | ||
}, function (reason) { | ||
return _wrap(cb()).then(function () { | ||
return _this5; | ||
}); | ||
}); | ||
} | ||
exports.finally = lastly; | ||
// ------------------------------------------------------------------- | ||
var _setFunctionNameAndLength = function () { | ||
var _defineProperties = Object.defineProperties; | ||
try { | ||
var f = _defineProperties(function () {}, { | ||
length: { value: 2 }, | ||
name: { value: 'foo' } | ||
}); | ||
if (f.length === 2 && f.name === 'foo') { | ||
return function (fn, name, length) { | ||
return _defineProperties(fn, { | ||
length: { | ||
configurable: true, | ||
value: length | ||
}, | ||
name: { | ||
configurable: true, | ||
value: name | ||
} | ||
}); | ||
}; | ||
} | ||
} catch (_) {} | ||
return function (fn) { | ||
return fn; | ||
}; | ||
}(); | ||
// Usage: promisify(fn, [ context ]) | ||
var promisify = exports.promisify = function promisify(fn, context) { | ||
return _setFunctionNameAndLength(function () { | ||
var _this6 = this; | ||
var length = arguments.length; | ||
var args = new Array(length + 1); | ||
for (var i = 0; i < length; ++i) { | ||
args[i] = arguments[i]; | ||
} | ||
return new Promise(function (resolve, reject) { | ||
args[length] = function (error, result) { | ||
return error ? reject(error) : resolve(result); | ||
}; | ||
fn.apply(context || _this6, args); | ||
}); | ||
}, fn.name, fn.length && fn.length - 1); | ||
}; | ||
var _DEFAULT_PALL_MAPPER = function _DEFAULT_PALL_MAPPER(name) { | ||
return !(_endsWith(name, 'Sync') || _endsWith(name, 'Async')) && name; | ||
}; | ||
// Usage: promisifyAll(obj, [ opts ]) | ||
var promisifyAll = exports.promisifyAll = function promisifyAll(obj) { | ||
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, | ||
_ref$mapper = _ref.mapper, | ||
mapper = _ref$mapper === undefined ? _DEFAULT_PALL_MAPPER : _ref$mapper, | ||
_ref$target = _ref.target, | ||
target = _ref$target === undefined ? {} : _ref$target, | ||
_ref$context = _ref.context, | ||
context = _ref$context === undefined ? obj : _ref$context; | ||
_forIn(obj, function (value, name) { | ||
var newName = void 0; | ||
if (typeof value === 'function' && (newName = mapper(name, value, obj))) { | ||
target[newName] = promisify(value, context); | ||
} | ||
}); | ||
return target; | ||
}; | ||
// ------------------------------------------------------------------- | ||
var FN_FALSE = function FN_FALSE() { | ||
return false; | ||
}; | ||
var FN_TRUE = function FN_TRUE() { | ||
return true; | ||
}; | ||
var _reflectResolution = function (__proto__) { | ||
return function (_value) { | ||
return { | ||
__proto__: __proto__, | ||
value: function value() { | ||
return _value; | ||
} | ||
}; | ||
}; | ||
}({ | ||
isFulfilled: FN_TRUE, | ||
isPending: FN_FALSE, | ||
isRejected: FN_FALSE, | ||
isResolved: FN_TRUE, | ||
reason: function reason() { | ||
throw new Error('no reason, the promise has resolved'); | ||
} | ||
}); | ||
var _reflectRejection = function (__proto__) { | ||
return function (_reason) { | ||
return { | ||
__proto__: __proto__, | ||
reason: function reason() { | ||
return _reason; | ||
} | ||
}; | ||
}; | ||
}({ | ||
isFulfilled: FN_FALSE, | ||
isPending: FN_FALSE, | ||
isRejected: FN_TRUE, | ||
isResolved: FN_FALSE, | ||
value: function value() { | ||
throw new Error('no value, the promise has rejected'); | ||
} | ||
}); | ||
// Returns a promise that is always successful when this promise is | ||
// settled. Its fulfillment value is an object that implements the | ||
// PromiseInspection interface and reflects the resolution this | ||
// promise. | ||
// | ||
// Usage: promise::reflect() | ||
function reflect() { | ||
return _wrap(this).then(_reflectResolution, _reflectRejection); | ||
} | ||
// ------------------------------------------------------------------- | ||
// Given a collection (array or object) which contains promises, | ||
// return a promise that is fulfilled when all the items in the | ||
// collection are either fulfilled or rejected. | ||
// | ||
// This promise will be fulfilled with a collection (of the same type, | ||
// array or object) containing promise inspections. | ||
// | ||
// Usage: promises::settle() | ||
function settle() { | ||
return all.call(this, function (x) { | ||
return reflect.call(x); | ||
}); | ||
} | ||
// ------------------------------------------------------------------- | ||
var _some = function _some(promises, count) { | ||
return new Promise(function (resolve, reject) { | ||
var values = []; | ||
var errors = []; | ||
var onFulfillment = function onFulfillment(value) { | ||
if (!values) { | ||
return; | ||
} | ||
values.push(value); | ||
if (--count === 0) { | ||
resolve(values); | ||
values = errors = null; | ||
} | ||
}; | ||
var acceptableErrors = -count; | ||
var onRejection = function onRejection(reason) { | ||
if (!values) { | ||
return; | ||
} | ||
errors.push(reason); | ||
if (--acceptableErrors === 0) { | ||
reject(errors); | ||
values = errors = null; | ||
} | ||
}; | ||
_forEach(promises, function (promise) { | ||
++acceptableErrors; | ||
_wrap(promise).then(onFulfillment, onRejection); | ||
}); | ||
}); | ||
}; | ||
// Usage: promises::some(count) | ||
function some(count) { | ||
return _wrap(this).then(function (promises) { | ||
return _some(promises, count); | ||
}); | ||
} | ||
// ------------------------------------------------------------------- | ||
function tap(onResolved, onRejected) { | ||
var _this7 = this; | ||
var forward = function forward() { | ||
return _this7; | ||
}; | ||
return _wrap(this).then(onResolved && function (value) { | ||
return _wrap(onResolved(value)).then(forward); | ||
}, onRejected && function (reason) { | ||
return _wrap(onRejected(reason)).then(forward); | ||
}); | ||
} | ||
// ------------------------------------------------------------------- | ||
var TimeoutError = exports.TimeoutError = function (_BaseError) { | ||
_inherits(TimeoutError, _BaseError); | ||
function TimeoutError() { | ||
_classCallCheck(this, TimeoutError); | ||
return _possibleConstructorReturn(this, (TimeoutError.__proto__ || Object.getPrototypeOf(TimeoutError)).call(this, 'operation timed out')); | ||
} | ||
return TimeoutError; | ||
}(_makeError.BaseError); | ||
// Usage: promise::timeout(ms, cb) | ||
function timeout(ms, cb) { | ||
var _this9 = this; | ||
return new Promise(function (resolve, reject) { | ||
var handle = setTimeout(function () { | ||
handle = null; | ||
if (typeof _this9.cancel === 'function') { | ||
_this9.cancel(); | ||
} | ||
if (cb) { | ||
try { | ||
resolve(cb()); | ||
} catch (error) { | ||
reject(error); | ||
} | ||
} else { | ||
reject(new TimeoutError()); | ||
} | ||
}, ms); | ||
_wrap(_this9).then(function (value) { | ||
handle !== null && clearTimeout(handle); | ||
resolve(value); | ||
}, function (reason) { | ||
handle !== null && clearTimeout(handle); | ||
reject(reason); | ||
}); | ||
}); | ||
} | ||
// ------------------------------------------------------------------- | ||
// Usage: fn::unpromisify() | ||
function unpromisify() { | ||
var fn = this; | ||
return _setFunctionNameAndLength(function () { | ||
var n = arguments.length - 1; | ||
var cb = void 0; | ||
if (n < 0 || typeof (cb = arguments[n]) !== 'function') { | ||
throw new Error('missing callback'); | ||
} | ||
var args = new Array(n); | ||
for (var i = 0; i < n; ++i) { | ||
args[i] = arguments[i]; | ||
} | ||
_wrapCall(fn, args, this).then(function (result) { | ||
return cb(null, result); | ||
}, function (reason) { | ||
return cb(reason); | ||
}); | ||
}, fn.name, fn.length + 1); | ||
} | ||
//# sourceMappingURL=index.js.map |
@@ -1,2 +0,1065 @@ | ||
'use strict';var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[],_n=!0,_d=!1,_e=void 0;try{for(var _s,_i=arr[Symbol.iterator]();!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!(i&&_arr.length===i));_n=!0);}catch(err){_d=!0,_e=err}finally{try{!_n&&_i['return']&&_i['return']()}finally{if(_d)throw _e}}return _arr}return function(arr,i){if(Array.isArray(arr))return arr;if(Symbol.iterator in Object(arr))return sliceIterator(arr,i);throw new TypeError('Invalid attempt to destructure non-iterable instance')}}(),_typeof='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&'function'==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj};var _makeError=require('make-error'),_makeError2=_interopRequireDefault(_makeError),_=require('./');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _asyncToGenerator(fn){return function(){var gen=fn.apply(this,arguments);return new Promise(function(resolve,reject){function step(key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}return info.done?void resolve(value):Promise.resolve(value).then(function(value){step('next',value)},function(err){step('throw',err)})}return step('next')})}}var identity=function identity(a){return a},noop=function noop(){},throwArg=function throwArg(a){throw a},rejectionOf=function rejectionOf(a){return a.then(throwArg,identity)};describe('all()',function(){it('with array',_asyncToGenerator(regeneratorRuntime.mark(function _callee(){var _context;return regeneratorRuntime.wrap(function _callee$(_context2){for(;1;)switch(_context2.prev=_context2.next){case 0:return _context2.t0=expect,_context2.next=3,(_context=[Promise.resolve('foo'),'bar'],_.all).call(_context);case 3:_context2.t1=_context2.sent,_context2.t2=['foo','bar'],(0,_context2.t0)(_context2.t1).toEqual(_context2.t2);case 6:case'end':return _context2.stop();}},_callee,void 0)}))),it('with object',_asyncToGenerator(regeneratorRuntime.mark(function _callee2(){var _context3;return regeneratorRuntime.wrap(function _callee2$(_context4){for(;1;)switch(_context4.prev=_context4.next){case 0:return _context4.t0=expect,_context4.next=3,(_context3={foo:Promise.resolve('foo'),bar:'bar'},_.all).call(_context3);case 3:_context4.t1=_context4.sent,_context4.t2={foo:'foo',bar:'bar'},(0,_context4.t0)(_context4.t1).toEqual(_context4.t2);case 6:case'end':return _context4.stop();}},_callee2,void 0)}))),it('resolve with empty collection',_asyncToGenerator(regeneratorRuntime.mark(function _callee3(){var _context5;return regeneratorRuntime.wrap(function _callee3$(_context6){for(;1;)switch(_context6.prev=_context6.next){case 0:return _context6.t0=expect,_context6.next=3,(_context5=[],_.all).call(_context5);case 3:_context6.t1=_context6.sent,_context6.t2=[],(0,_context6.t0)(_context6.t1).toEqual(_context6.t2);case 6:case'end':return _context6.stop();}},_callee3,void 0)}))),it('rejects first rejection',_asyncToGenerator(regeneratorRuntime.mark(function _callee4(){var _context7;return regeneratorRuntime.wrap(function _callee4$(_context8){for(;1;)switch(_context8.prev=_context8.next){case 0:return _context8.t0=expect,_context8.next=3,rejectionOf((_context7=['foo',Promise.reject('bar')],_.all).call(_context7));case 3:_context8.t1=_context8.sent,(0,_context8.t0)(_context8.t1).toBe('bar');case 5:case'end':return _context8.stop();}},_callee4,void 0)}))),it('rejects first rejection (even with pending promises)',_asyncToGenerator(regeneratorRuntime.mark(function _callee5(){var _context9;return regeneratorRuntime.wrap(function _callee5$(_context10){for(;1;)switch(_context10.prev=_context10.next){case 0:return _context10.t0=expect,_context10.next=3,rejectionOf((_context9=[new Promise(function(){}),Promise.reject('bar')],_.all).call(_context9));case 3:_context10.t1=_context10.sent,(0,_context10.t0)(_context10.t1).toBe('bar');case 5:case'end':return _context10.stop();}},_callee5,void 0)})))}),describe('CancelToken',function(){describe('.isCancelToken()',function(){it('determines whether the passed value is a CancelToken',function(){expect(_.CancelToken.isCancelToken(null)).toBe(!1),expect(_.CancelToken.isCancelToken({})).toBe(!1),expect(_.CancelToken.isCancelToken(new _.CancelToken(noop))).toBe(!0)})}),describe('.source()',function(){it('creates a new token',function(){var _CancelToken$source=_.CancelToken.source(),a=_CancelToken$source.cancel,b=_CancelToken$source.token;expect(b.requested).toBe(!1),a(),expect(b.requested).toBe(!0)})}),describe('#promise',function(){it('returns a promise resolving on cancel',_asyncToGenerator(regeneratorRuntime.mark(function _callee6(){var _CancelToken$source2,a,b,c,d;return regeneratorRuntime.wrap(function _callee6$(_context11){for(;1;)switch(_context11.prev=_context11.next){case 0:return _CancelToken$source2=_.CancelToken.source(),a=_CancelToken$source2.cancel,b=_CancelToken$source2.token,c=b.promise,a('foo'),_context11.next=4,c;case 4:d=_context11.sent,expect(d).toBeInstanceOf(_.Cancel),expect(d.message).toBe('foo');case 6:case'end':return _context11.stop();}},_callee6,void 0)})))}),describe('#requested',function(){it('synchronously returns whether cancellation has been requested',function(){var _CancelToken$source3=_.CancelToken.source(),a=_CancelToken$source3.cancel,b=_CancelToken$source3.token;expect(b.requested).toBe(!1),a(),expect(b.requested).toBe(!0)})}),describe('#throwIfRequested',function(){it('synchronously throws if cancellation has been requested',function(){var _CancelToken$source4=_.CancelToken.source(),a=_CancelToken$source4.cancel,b=_CancelToken$source4.token;b.throwIfRequested(),a('foo');try{b.throwIfRequested(),expect(!1).toBe('should have thrown')}catch(c){expect(c).toBeInstanceOf(_.Cancel),expect(c.message).toBe('foo')}})})}),describe('catchPlus',function(){it('catches errors matching a predicate',_asyncToGenerator(regeneratorRuntime.mark(function _callee7(){var _context12,a=function a(b){return'foo'===b};return regeneratorRuntime.wrap(function _callee7$(_context13){for(;1;)switch(_context13.prev=_context13.next){case 0:return _context13.t0=expect,_context13.next=3,(_context12=Promise.reject('foo'),_.catchPlus).call(_context12,a,identity);case 3:return _context13.t1=_context13.sent,(0,_context13.t0)(_context13.t1).toBe('foo'),_context13.t2=expect,_context13.next=8,rejectionOf((_context12=Promise.reject('bar'),_.catchPlus).call(_context12,a,identity));case 8:_context13.t3=_context13.sent,(0,_context13.t2)(_context13.t3).toBe('bar');case 10:case'end':return _context13.stop();}},_callee7,void 0)}))),it('catches errors matching a class',_asyncToGenerator(regeneratorRuntime.mark(function _callee8(){var _context14,a=(0,_makeError2.default)('CustomError1'),b=(0,_makeError2.default)('CustomError2'),c=new a;return regeneratorRuntime.wrap(function _callee8$(_context15){for(;1;)switch(_context15.prev=_context15.next){case 0:return _context15.t0=expect,_context15.next=3,(_context14=Promise.reject(c),_.catchPlus).call(_context14,a,identity);case 3:return _context15.t1=_context15.sent,_context15.t2=c,(0,_context15.t0)(_context15.t1).toBe(_context15.t2),_context15.t3=expect,_context15.next=9,(_context14=Promise.reject(c),_.catchPlus).call(_context14,Error,identity);case 9:return _context15.t4=_context15.sent,_context15.t5=c,(0,_context15.t3)(_context15.t4).toBe(_context15.t5),_context15.t6=expect,_context15.next=15,rejectionOf((_context14=Promise.reject(c),_.catchPlus).call(_context14,b,identity));case 15:_context15.t7=_context15.sent,_context15.t8=c,(0,_context15.t6)(_context15.t7).toBe(_context15.t8);case 18:case'end':return _context15.stop();}},_callee8,void 0)}))),it('catches errors matching an object pattern',_asyncToGenerator(regeneratorRuntime.mark(function _callee9(){var _context16,a={foo:0};return regeneratorRuntime.wrap(function _callee9$(_context17){for(;1;)switch(_context17.prev=_context17.next){case 0:return _context17.t0=expect,_context17.t1=_typeof,_context17.next=4,(_context16=Promise.reject({foo:0}),_.catchPlus).call(_context16,a,identity);case 4:return _context17.t2=_context17.sent,_context17.t3=(0,_context17.t1)(_context17.t2),(0,_context17.t0)(_context17.t3).toBe('object'),_context17.t4=expect,_context17.t5=_typeof,_context17.next=11,rejectionOf((_context16=Promise.reject({foo:1}),_.catchPlus).call(_context16,a,identity));case 11:return _context17.t6=_context17.sent,_context17.t7=(0,_context17.t5)(_context17.t6),(0,_context17.t4)(_context17.t7).toBe('object'),_context17.t8=expect,_context17.t9=_typeof,_context17.next=18,rejectionOf((_context16=Promise.reject({bar:0}),_.catchPlus).call(_context16,a,identity));case 18:_context17.t10=_context17.sent,_context17.t11=(0,_context17.t9)(_context17.t10),(0,_context17.t8)(_context17.t11).toBe('object');case 21:case'end':return _context17.stop();}},_callee9,void 0)}))),it('does not catch programmer errors',_asyncToGenerator(regeneratorRuntime.mark(function _callee10(){var _context18;return regeneratorRuntime.wrap(function _callee10$(_context19){for(;1;)switch(_context19.prev=_context19.next){case 0:return _context19.t0=expect,_context19.next=3,rejectionOf((_context18=Promise.reject(new TypeError('')),_.catchPlus).call(_context18,identity));case 3:return _context19.t1=_context19.sent,_context19.t2=TypeError,(0,_context19.t0)(_context19.t1).toBeInstanceOf(_context19.t2),_context19.t3=expect,_context19.next=9,rejectionOf((_context18=Promise.reject(new SyntaxError('')),_.catchPlus).call(_context18,identity));case 9:return _context19.t4=_context19.sent,_context19.t5=SyntaxError,(0,_context19.t3)(_context19.t4).toBeInstanceOf(_context19.t5),_context19.t6=expect,_context19.next=15,(_context18=Promise.reject(new TypeError('')),_.catchPlus).call(_context18,TypeError,identity);case 15:_context19.t7=_context19.sent,_context19.t8=TypeError,(0,_context19.t6)(_context19.t7).toBeInstanceOf(_context19.t8);case 18:case'end':return _context19.stop();}},_callee10,void 0)})))}),describe('forArray()',function(){it('iterates over an array of promises',_asyncToGenerator(regeneratorRuntime.mark(function _callee11(){var a,b;return regeneratorRuntime.wrap(function _callee11$(_context20){for(;1;)switch(_context20.prev=_context20.next){case 0:return a=jest.fn(),b=[Promise.resolve('foo'),Promise.resolve('bar'),'baz'],_context20.t0=expect,_context20.next=4,_.forArray.call(b,a);case 4:return _context20.t1=_context20.sent,(0,_context20.t0)(_context20.t1).not.toBeDefined(),_context20.t2=expect,_context20.next=9,a.mock.calls;case 9:_context20.t3=_context20.sent,_context20.t4=[['foo',0,b],['bar',1,b],['baz',2,b]],(0,_context20.t2)(_context20.t3).toEqual(_context20.t4);case 12:case'end':return _context20.stop();}},_callee11,void 0)})))}),describe('fromCallback()',function(){it('creates a promise which resolves with value passed to the callback',_asyncToGenerator(regeneratorRuntime.mark(function _callee12(){return regeneratorRuntime.wrap(function _callee12$(_context21){for(;1;)switch(_context21.prev=_context21.next){case 0:return _context21.t0=expect,_context21.next=3,(0,_.fromCallback)(function(a){return a(null,'foo')});case 3:_context21.t1=_context21.sent,(0,_context21.t0)(_context21.t1).toBe('foo');case 5:case'end':return _context21.stop();}},_callee12,void 0)}))),it('creates a promise which rejects with reason passed to the callback',_asyncToGenerator(regeneratorRuntime.mark(function _callee13(){return regeneratorRuntime.wrap(function _callee13$(_context22){for(;1;)switch(_context22.prev=_context22.next){case 0:return _context22.t0=expect,_context22.next=3,rejectionOf((0,_.fromCallback)(function(a){return a('bar')}));case 3:_context22.t1=_context22.sent,(0,_context22.t0)(_context22.t1).toBe('bar');case 5:case'end':return _context22.stop();}},_callee13,void 0)})))}),describe('join()',function(){it('calls the callback once promises are resolved',function(){return(0,_.join)(Promise.resolve('foo'),Promise.resolve('bar'),function(a,b){expect(a).toBe('foo'),expect(b).toBe('bar')})}),it('can takes inputs in an array',function(){return(0,_.join)([Promise.resolve('foo'),Promise.resolve('bar')],function(a,b){expect(a).toBe('foo'),expect(b).toBe('bar')})}),it('rejects if one promise rejects',_asyncToGenerator(regeneratorRuntime.mark(function _callee14(){return regeneratorRuntime.wrap(function _callee14$(_context23){for(;1;)switch(_context23.prev=_context23.next){case 0:return _context23.t0=expect,_context23.next=3,rejectionOf((0,_.join)(Promise.resolve('foo'),Promise.reject('bar'),function(a,b){expect(a).toBe('foo'),expect(b).toBe('bar')}));case 3:_context23.t1=_context23.sent,(0,_context23.t0)(_context23.t1).toBe('bar');case 5:case'end':return _context23.stop();}},_callee14,void 0)})))}),describe('lastly()',function(){it('calls a callback on resolution',_asyncToGenerator(regeneratorRuntime.mark(function _callee15(){var _context24,a={},b=jest.fn();return regeneratorRuntime.wrap(function _callee15$(_context25){for(;1;)switch(_context25.prev=_context25.next){case 0:return _context25.t0=expect,_context25.next=3,(_context24=Promise.resolve(a),_.lastly).call(_context24,b);case 3:_context25.t1=_context25.sent,_context25.t2=a,(0,_context25.t0)(_context25.t1).toBe(_context25.t2),expect(b).toHaveBeenCalledTimes(1);case 7:case'end':return _context25.stop();}},_callee15,void 0)}))),it('calls a callback on rejection',_asyncToGenerator(regeneratorRuntime.mark(function _callee16(){var _context26,a={},b=jest.fn();return regeneratorRuntime.wrap(function _callee16$(_context27){for(;1;)switch(_context27.prev=_context27.next){case 0:return _context27.t0=expect,_context27.next=3,rejectionOf((_context26=Promise.reject(a),_.lastly).call(_context26,b));case 3:_context27.t1=_context27.sent,_context27.t2=a,(0,_context27.t0)(_context27.t1).toBe(_context27.t2),expect(b).toHaveBeenCalledTimes(1);case 7:case'end':return _context27.stop();}},_callee16,void 0)})))}),describe('promisifyAll()',function(){it('returns a new object',function(){var a={},b=(0,_.promisifyAll)(a);expect('undefined'==typeof b?'undefined':_typeof(b)).toBe('object'),expect(b).not.toBe(a)}),it('creates promisified version of all functions bound to the original object',_asyncToGenerator(regeneratorRuntime.mark(function _callee17(){var a,b;return regeneratorRuntime.wrap(function _callee17$(_context28){for(;1;)switch(_context28.prev=_context28.next){case 0:return a={foo:function foo(c){c(null,this)}},b=(0,_.promisifyAll)(a),_context28.t0=expect,_context28.next=4,b.foo();case 4:_context28.t1=_context28.sent,_context28.t2=a,(0,_context28.t0)(_context28.t1).toBe(_context28.t2);case 7:case'end':return _context28.stop();}},_callee17,void 0)}))),it('ignores functions ending with Sync or Async',function(){var a={fooAsync:function fooAsync(){},fooSync:function fooSync(){}},b=_.promisifyAll.call(a);expect(b.foo).not.toBeDefined(),expect(b.fooASync).not.toBeDefined(),expect(b.fooSync).not.toBeDefined()})}),describe('settle()',function(){it('works with arrays',function(){var _context29;return(_context29=[Promise.resolve(42),Math.PI,Promise.reject('fatality')],_.settle).call(_context29).then(function(_ref18){var _ref19=_slicedToArray(_ref18,3),a=_ref19[0],b=_ref19[1],c=_ref19[2];expect(a.isFulfilled()).toBe(!0),expect(b.isFulfilled()).toBe(!0),expect(c.isFulfilled()).toBe(!1),expect(a.isResolved()).toBe(!0),expect(b.isResolved()).toBe(!0),expect(c.isResolved()).toBe(!1),expect(a.isRejected()).toBe(!1),expect(b.isRejected()).toBe(!1),expect(c.isRejected()).toBe(!0),expect(a.value()).toBe(42),expect(b.value()).toBe(Math.PI),expect(c.value.bind(c)).toThrow(),expect(a.reason.bind(a)).toThrow(),expect(b.reason.bind(b)).toThrow(),expect(c.reason()).toBe('fatality')})}),it('works with objects',function(){var _context30;return(_context30={a:Promise.resolve(42),b:Math.PI,c:Promise.reject('fatality')},_.settle).call(_context30).then(function(_ref20){var a=_ref20.a,b=_ref20.b,c=_ref20.c;expect(a.isFulfilled()).toBe(!0),expect(b.isFulfilled()).toBe(!0),expect(c.isFulfilled()).toBe(!1),expect(a.isResolved()).toBe(!0),expect(b.isResolved()).toBe(!0),expect(c.isResolved()).toBe(!1),expect(a.isRejected()).toBe(!1),expect(b.isRejected()).toBe(!1),expect(c.isRejected()).toBe(!0),expect(a.value()).toBe(42),expect(b.value()).toBe(Math.PI),expect(c.value.bind(c)).toThrow(),expect(a.reason.bind(a)).toThrow(),expect(b.reason.bind(b)).toThrow(),expect(c.reason()).toBe('fatality')})})}),describe('tap(cb)',function(){it('call cb with the resolved value',function(){return new Promise(function(a){var _context31;(_context31=Promise.resolve('value'),_.tap).call(_context31,function(b){expect(b).toBe('value'),a()})})}),it('does not call cb if the promise is rejected',_asyncToGenerator(regeneratorRuntime.mark(function _callee18(){var _context32;return regeneratorRuntime.wrap(function _callee18$(_context33){for(;1;)switch(_context33.prev=_context33.next){case 0:return _context33.t0=expect,_context33.next=3,rejectionOf((_context32=Promise.reject('reason'),_.tap).call(_context32,function(){return Promise.reject('other reason')}));case 3:_context33.t1=_context33.sent,(0,_context33.t0)(_context33.t1).toBe('reason');case 5:case'end':return _context33.stop();}},_callee18,void 0)}))),it('forwards the resolved value',_asyncToGenerator(regeneratorRuntime.mark(function _callee19(){var _context34;return regeneratorRuntime.wrap(function _callee19$(_context35){for(;1;)switch(_context35.prev=_context35.next){case 0:return _context35.t0=expect,_context35.next=3,(_context34=Promise.resolve('value'),_.tap).call(_context34,function(){return'other value'});case 3:_context35.t1=_context35.sent,(0,_context35.t0)(_context35.t1).toBe('value');case 5:case'end':return _context35.stop();}},_callee19,void 0)}))),it('rejects if cb rejects',_asyncToGenerator(regeneratorRuntime.mark(function _callee20(){var _context36;return regeneratorRuntime.wrap(function _callee20$(_context37){for(;1;)switch(_context37.prev=_context37.next){case 0:return _context37.t0=expect,_context37.next=3,rejectionOf((_context36=Promise.resolve('value'),_.tap).call(_context36,function(){return Promise.reject('reason')}));case 3:_context37.t1=_context37.sent,(0,_context37.t0)(_context37.t1).toBe('reason');case 5:case'end':return _context37.stop();}},_callee20,void 0)})))}),describe('tap(null, cb)',function(){it('call cb with the rejected reason',function(){return new Promise(function(a){var _context38;(_context38=Promise.reject('reason'),_.tap).call(_context38,null,function(b){expect(b).toBe('reason'),a()}).catch(function(){})})}),it('does not call cb if the promise is resolved',_asyncToGenerator(regeneratorRuntime.mark(function _callee21(){var _context39;return regeneratorRuntime.wrap(function _callee21$(_context40){for(;1;)switch(_context40.prev=_context40.next){case 0:return _context40.t0=expect,_context40.next=3,(_context39=Promise.resolve('value'),_.tap).call(_context39,null,function(){return Promise.reject('other reason')});case 3:_context40.t1=_context40.sent,(0,_context40.t0)(_context40.t1).toBe('value');case 5:case'end':return _context40.stop();}},_callee21,void 0)}))),it('forwards the rejected reason',_asyncToGenerator(regeneratorRuntime.mark(function _callee22(){var _context41;return regeneratorRuntime.wrap(function _callee22$(_context42){for(;1;)switch(_context42.prev=_context42.next){case 0:return _context42.t0=expect,_context42.next=3,rejectionOf((_context41=Promise.reject('reason'),_.tap).call(_context41,null,function(){return'value'}));case 3:_context42.t1=_context42.sent,(0,_context42.t0)(_context42.t1).toBe('reason');case 5:case'end':return _context42.stop();}},_callee22,void 0)}))),it('rejects if cb rejects',_asyncToGenerator(regeneratorRuntime.mark(function _callee23(){var _context43;return regeneratorRuntime.wrap(function _callee23$(_context44){for(;1;)switch(_context44.prev=_context44.next){case 0:return _context44.t0=expect,_context44.next=3,rejectionOf((_context43=Promise.reject('reason'),_.tap).call(_context43,null,function(){return Promise.reject('other reason')}));case 3:_context44.t1=_context44.sent,(0,_context44.t0)(_context44.t1).toBe('other reason');case 5:case'end':return _context44.stop();}},_callee23,void 0)})))}),describe('timeout()',function(){var a=new Promise(function(){});it('rejects a promise if not settled after a delay',_asyncToGenerator(regeneratorRuntime.mark(function _callee24(){return regeneratorRuntime.wrap(function _callee24$(_context45){for(;1;)switch(_context45.prev=_context45.next){case 0:return _context45.t0=expect,_context45.next=3,rejectionOf(_.timeout.call(a,10));case 3:_context45.t1=_context45.sent,_context45.t2=_.TimeoutError,(0,_context45.t0)(_context45.t1).toBeInstanceOf(_context45.t2);case 6:case'end':return _context45.stop();}},_callee24,void 0)}))),it('call the callback if not settled after a delay',_asyncToGenerator(regeneratorRuntime.mark(function _callee25(){return regeneratorRuntime.wrap(function _callee25$(_context46){for(;1;)switch(_context46.prev=_context46.next){case 0:return _context46.t0=expect,_context46.next=3,_.timeout.call(a,10,function(){return'bar'});case 3:_context46.t1=_context46.sent,(0,_context46.t0)(_context46.t1).toBe('bar');case 5:case'end':return _context46.stop();}},_callee25,void 0)}))),it('forwards the settlement if settled before a delay',_asyncToGenerator(regeneratorRuntime.mark(function _callee26(){var _context47;return regeneratorRuntime.wrap(function _callee26$(_context48){for(;1;)switch(_context48.prev=_context48.next){case 0:return _context48.t0=expect,_context48.next=3,(_context47=Promise.resolve('value'),_.timeout).call(_context47,10);case 3:return _context48.t1=_context48.sent,(0,_context48.t0)(_context48.t1).toBe('value'),_context48.t2=expect,_context48.next=8,rejectionOf((_context47=Promise.reject('reason'),_.timeout).call(_context47,10));case 8:_context48.t3=_context48.sent,(0,_context48.t2)(_context48.t3).toBe('reason');case 10:case'end':return _context48.stop();}},_callee26,void 0)}))),it('rejects if cb throws synchronously',_asyncToGenerator(regeneratorRuntime.mark(function _callee27(){return regeneratorRuntime.wrap(function _callee27$(_context49){for(;1;)switch(_context49.prev=_context49.next){case 0:return _context49.t0=expect,_context49.next=3,rejectionOf(_.timeout.call(a,10,function(){throw'reason'}));case 3:_context49.t1=_context49.sent,(0,_context49.t0)(_context49.t1).toBe('reason');case 5:case'end':return _context49.stop();}},_callee27,void 0)})))}),describe('unpromisify()',function(){it('forwards the result',function(a){var b=_.unpromisify.call(function(){return Promise.resolve('foo')});b(function(c,d){expect(c).toBe(null),expect(d).toBe('foo'),a()})}),it('forwards the error',function(a){var b=_.unpromisify.call(function(){return Promise.reject('foo')});b(function(c){expect(c).toBe('foo'),a()})})}); | ||
'use strict'; | ||
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); | ||
var _makeError = require('make-error'); | ||
var _makeError2 = _interopRequireDefault(_makeError); | ||
var _ = require('./'); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* eslint-env jest */ | ||
// =================================================================== | ||
var identity = function identity(value) { | ||
return value; | ||
}; | ||
var noop = function noop() {}; | ||
var throwArg = function throwArg(value) { | ||
throw value; | ||
}; | ||
// swap resolution/rejection of a promise to help test rejection | ||
var rejectionOf = function rejectionOf(promise) { | ||
return promise.then(throwArg, identity); | ||
}; | ||
// =================================================================== | ||
// work around prefer-promise-reject-errors | ||
var reject = function reject(value) { | ||
return Promise.reject(value); | ||
}; | ||
describe('all()', function () { | ||
it('with array', _asyncToGenerator(regeneratorRuntime.mark(function _callee() { | ||
var _context; | ||
return regeneratorRuntime.wrap(function _callee$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
_context2.t0 = expect; | ||
_context2.next = 3; | ||
return (_context = [Promise.resolve('foo'), 'bar'], _.all).call(_context); | ||
case 3: | ||
_context2.t1 = _context2.sent; | ||
_context2.t2 = ['foo', 'bar']; | ||
(0, _context2.t0)(_context2.t1).toEqual(_context2.t2); | ||
case 6: | ||
case 'end': | ||
return _context2.stop(); | ||
} | ||
} | ||
}, _callee, undefined); | ||
}))); | ||
it('with object', _asyncToGenerator(regeneratorRuntime.mark(function _callee2() { | ||
var _context3; | ||
return regeneratorRuntime.wrap(function _callee2$(_context4) { | ||
while (1) { | ||
switch (_context4.prev = _context4.next) { | ||
case 0: | ||
_context4.t0 = expect; | ||
_context4.next = 3; | ||
return (_context3 = { | ||
foo: Promise.resolve('foo'), | ||
bar: 'bar' | ||
}, _.all).call(_context3); | ||
case 3: | ||
_context4.t1 = _context4.sent; | ||
_context4.t2 = { | ||
foo: 'foo', | ||
bar: 'bar' | ||
}; | ||
(0, _context4.t0)(_context4.t1).toEqual(_context4.t2); | ||
case 6: | ||
case 'end': | ||
return _context4.stop(); | ||
} | ||
} | ||
}, _callee2, undefined); | ||
}))); | ||
it('resolve with empty collection', _asyncToGenerator(regeneratorRuntime.mark(function _callee3() { | ||
var _context5; | ||
return regeneratorRuntime.wrap(function _callee3$(_context6) { | ||
while (1) { | ||
switch (_context6.prev = _context6.next) { | ||
case 0: | ||
_context6.t0 = expect; | ||
_context6.next = 3; | ||
return (_context5 = [], _.all).call(_context5); | ||
case 3: | ||
_context6.t1 = _context6.sent; | ||
_context6.t2 = []; | ||
(0, _context6.t0)(_context6.t1).toEqual(_context6.t2); | ||
case 6: | ||
case 'end': | ||
return _context6.stop(); | ||
} | ||
} | ||
}, _callee3, undefined); | ||
}))); | ||
it('rejects first rejection', _asyncToGenerator(regeneratorRuntime.mark(function _callee4() { | ||
var _context7; | ||
return regeneratorRuntime.wrap(function _callee4$(_context8) { | ||
while (1) { | ||
switch (_context8.prev = _context8.next) { | ||
case 0: | ||
_context8.t0 = expect; | ||
_context8.next = 3; | ||
return rejectionOf((_context7 = ['foo', reject('bar')], _.all).call(_context7)); | ||
case 3: | ||
_context8.t1 = _context8.sent; | ||
(0, _context8.t0)(_context8.t1).toBe('bar'); | ||
case 5: | ||
case 'end': | ||
return _context8.stop(); | ||
} | ||
} | ||
}, _callee4, undefined); | ||
}))); | ||
it('rejects first rejection (even with pending promises)', _asyncToGenerator(regeneratorRuntime.mark(function _callee5() { | ||
var _context9; | ||
return regeneratorRuntime.wrap(function _callee5$(_context10) { | ||
while (1) { | ||
switch (_context10.prev = _context10.next) { | ||
case 0: | ||
_context10.t0 = expect; | ||
_context10.next = 3; | ||
return rejectionOf((_context9 = [new Promise(function () {}), reject('bar')], _.all).call(_context9)); | ||
case 3: | ||
_context10.t1 = _context10.sent; | ||
(0, _context10.t0)(_context10.t1).toBe('bar'); | ||
case 5: | ||
case 'end': | ||
return _context10.stop(); | ||
} | ||
} | ||
}, _callee5, undefined); | ||
}))); | ||
}); | ||
// ------------------------------------------------------------------- | ||
describe('CancelToken', function () { | ||
describe('.isCancelToken()', function () { | ||
it('determines whether the passed value is a CancelToken', function () { | ||
expect(_.CancelToken.isCancelToken(null)).toBe(false); | ||
expect(_.CancelToken.isCancelToken({})).toBe(false); | ||
expect(_.CancelToken.isCancelToken(new _.CancelToken(noop))).toBe(true); | ||
}); | ||
}); | ||
describe('.source()', function () { | ||
it('creates a new token', function () { | ||
var _CancelToken$source = _.CancelToken.source(), | ||
cancel = _CancelToken$source.cancel, | ||
token = _CancelToken$source.token; | ||
expect(token.requested).toBe(false); | ||
cancel(); | ||
expect(token.requested).toBe(true); | ||
}); | ||
}); | ||
describe('#promise', function () { | ||
it('returns a promise resolving on cancel', _asyncToGenerator(regeneratorRuntime.mark(function _callee6() { | ||
var _CancelToken$source2, cancel, token, promise, value; | ||
return regeneratorRuntime.wrap(function _callee6$(_context11) { | ||
while (1) { | ||
switch (_context11.prev = _context11.next) { | ||
case 0: | ||
_CancelToken$source2 = _.CancelToken.source(), cancel = _CancelToken$source2.cancel, token = _CancelToken$source2.token; | ||
promise = token.promise; | ||
cancel('foo'); | ||
_context11.next = 5; | ||
return promise; | ||
case 5: | ||
value = _context11.sent; | ||
expect(value).toBeInstanceOf(_.Cancel); | ||
expect(value.message).toBe('foo'); | ||
case 8: | ||
case 'end': | ||
return _context11.stop(); | ||
} | ||
} | ||
}, _callee6, undefined); | ||
}))); | ||
}); | ||
describe('#race', function () { | ||
it('returns a token which resolve synchronously', function () { | ||
var _CancelToken$source3 = _.CancelToken.source(), | ||
cancel = _CancelToken$source3.cancel, | ||
token = _CancelToken$source3.token; | ||
var raceToken = _.CancelToken.race([new _.CancelToken(noop), token]); | ||
expect(raceToken.reason).toBeUndefined(); | ||
cancel(); | ||
expect(raceToken.reason).toBe(token.reason); | ||
}); | ||
}); | ||
describe('#reason', function () { | ||
it('synchronously returns the cancellation reason', function () { | ||
var _CancelToken$source4 = _.CancelToken.source(), | ||
cancel = _CancelToken$source4.cancel, | ||
token = _CancelToken$source4.token; | ||
expect(token.reason).toBeUndefined(); | ||
cancel('foo'); | ||
expect(token.reason.message).toBe('foo'); | ||
}); | ||
}); | ||
describe('#requested', function () { | ||
it('synchronously returns whether cancellation has been requested', function () { | ||
var _CancelToken$source5 = _.CancelToken.source(), | ||
cancel = _CancelToken$source5.cancel, | ||
token = _CancelToken$source5.token; | ||
expect(token.requested).toBe(false); | ||
cancel(); | ||
expect(token.requested).toBe(true); | ||
}); | ||
}); | ||
describe('#throwIfRequested', function () { | ||
it('synchronously throws if cancellation has been requested', function () { | ||
var _CancelToken$source6 = _.CancelToken.source(), | ||
cancel = _CancelToken$source6.cancel, | ||
token = _CancelToken$source6.token; | ||
token.throwIfRequested(); | ||
cancel('foo'); | ||
try { | ||
token.throwIfRequested(); | ||
expect(false).toBe('should have thrown'); | ||
} catch (error) { | ||
expect(error).toBeInstanceOf(_.Cancel); | ||
expect(error.message).toBe('foo'); | ||
} | ||
}); | ||
}); | ||
}); | ||
// ------------------------------------------------------------------- | ||
describe('catchPlus', function () { | ||
it('catches errors matching a predicate', _asyncToGenerator(regeneratorRuntime.mark(function _callee7() { | ||
var _context12; | ||
var predicate; | ||
return regeneratorRuntime.wrap(function _callee7$(_context13) { | ||
while (1) { | ||
switch (_context13.prev = _context13.next) { | ||
case 0: | ||
predicate = function predicate(reason) { | ||
return reason === 'foo'; | ||
}; | ||
_context13.t0 = expect; | ||
_context13.next = 4; | ||
return (_context12 = reject('foo'), _.catchPlus).call(_context12, predicate, identity); | ||
case 4: | ||
_context13.t1 = _context13.sent; | ||
(0, _context13.t0)(_context13.t1).toBe('foo'); | ||
_context13.t2 = expect; | ||
_context13.next = 9; | ||
return rejectionOf((_context12 = reject('bar'), _.catchPlus).call(_context12, predicate, identity)); | ||
case 9: | ||
_context13.t3 = _context13.sent; | ||
(0, _context13.t2)(_context13.t3).toBe('bar'); | ||
case 11: | ||
case 'end': | ||
return _context13.stop(); | ||
} | ||
} | ||
}, _callee7, undefined); | ||
}))); | ||
it('catches errors matching a class', _asyncToGenerator(regeneratorRuntime.mark(function _callee8() { | ||
var _context14; | ||
var CustomError1, CustomError2, error; | ||
return regeneratorRuntime.wrap(function _callee8$(_context15) { | ||
while (1) { | ||
switch (_context15.prev = _context15.next) { | ||
case 0: | ||
CustomError1 = (0, _makeError2.default)('CustomError1'); | ||
CustomError2 = (0, _makeError2.default)('CustomError2'); | ||
error = new CustomError1(); | ||
// The class itself. | ||
_context15.t0 = expect; | ||
_context15.next = 6; | ||
return (_context14 = Promise.reject(error), _.catchPlus).call(_context14, CustomError1, identity); | ||
case 6: | ||
_context15.t1 = _context15.sent; | ||
_context15.t2 = error; | ||
(0, _context15.t0)(_context15.t1).toBe(_context15.t2); | ||
_context15.t3 = expect; | ||
_context15.next = 12; | ||
return (_context14 = Promise.reject(error), _.catchPlus).call(_context14, Error, identity); | ||
case 12: | ||
_context15.t4 = _context15.sent; | ||
_context15.t5 = error; | ||
(0, _context15.t3)(_context15.t4).toBe(_context15.t5); | ||
_context15.t6 = expect; | ||
_context15.next = 18; | ||
return rejectionOf((_context14 = Promise.reject(error), _.catchPlus).call(_context14, CustomError2, identity)); | ||
case 18: | ||
_context15.t7 = _context15.sent; | ||
_context15.t8 = error; | ||
(0, _context15.t6)(_context15.t7).toBe(_context15.t8); | ||
case 21: | ||
case 'end': | ||
return _context15.stop(); | ||
} | ||
} | ||
}, _callee8, undefined); | ||
}))); | ||
it('catches errors matching an object pattern', _asyncToGenerator(regeneratorRuntime.mark(function _callee9() { | ||
var _context16; | ||
var predicate; | ||
return regeneratorRuntime.wrap(function _callee9$(_context17) { | ||
while (1) { | ||
switch (_context17.prev = _context17.next) { | ||
case 0: | ||
predicate = { foo: 0 }; | ||
_context17.t0 = expect; | ||
_context17.next = 4; | ||
return (_context16 = reject({ foo: 0 }), _.catchPlus).call(_context16, predicate, identity); | ||
case 4: | ||
_context17.t1 = typeof _context17.sent; | ||
(0, _context17.t0)(_context17.t1).toBe('object'); | ||
_context17.t2 = expect; | ||
_context17.next = 9; | ||
return rejectionOf((_context16 = reject({ foo: 1 }), _.catchPlus).call(_context16, predicate, identity)); | ||
case 9: | ||
_context17.t3 = typeof _context17.sent; | ||
(0, _context17.t2)(_context17.t3).toBe('object'); | ||
_context17.t4 = expect; | ||
_context17.next = 14; | ||
return rejectionOf((_context16 = reject({ bar: 0 }), _.catchPlus).call(_context16, predicate, identity)); | ||
case 14: | ||
_context17.t5 = typeof _context17.sent; | ||
(0, _context17.t4)(_context17.t5).toBe('object'); | ||
case 16: | ||
case 'end': | ||
return _context17.stop(); | ||
} | ||
} | ||
}, _callee9, undefined); | ||
}))); | ||
it('does not catch programmer errors', _asyncToGenerator(regeneratorRuntime.mark(function _callee10() { | ||
var _context18; | ||
return regeneratorRuntime.wrap(function _callee10$(_context19) { | ||
while (1) { | ||
switch (_context19.prev = _context19.next) { | ||
case 0: | ||
_context19.t0 = expect; | ||
_context19.next = 3; | ||
return rejectionOf((_context18 = Promise.reject(new TypeError('')), _.catchPlus).call(_context18, identity)); | ||
case 3: | ||
_context19.t1 = _context19.sent; | ||
_context19.t2 = TypeError; | ||
(0, _context19.t0)(_context19.t1).toBeInstanceOf(_context19.t2); | ||
_context19.t3 = expect; | ||
_context19.next = 9; | ||
return rejectionOf((_context18 = Promise.reject(new SyntaxError('')), _.catchPlus).call(_context18, identity)); | ||
case 9: | ||
_context19.t4 = _context19.sent; | ||
_context19.t5 = SyntaxError; | ||
(0, _context19.t3)(_context19.t4).toBeInstanceOf(_context19.t5); | ||
_context19.t6 = expect; | ||
_context19.next = 15; | ||
return (_context18 = Promise.reject(new TypeError('')), _.catchPlus).call(_context18, TypeError, identity); | ||
case 15: | ||
_context19.t7 = _context19.sent; | ||
_context19.t8 = TypeError; | ||
(0, _context19.t6)(_context19.t7).toBeInstanceOf(_context19.t8); | ||
case 18: | ||
case 'end': | ||
return _context19.stop(); | ||
} | ||
} | ||
}, _callee10, undefined); | ||
}))); | ||
}); | ||
// ------------------------------------------------------------------- | ||
describe('forArray()', function () { | ||
it('iterates over an array of promises', _asyncToGenerator(regeneratorRuntime.mark(function _callee11() { | ||
var spy, array; | ||
return regeneratorRuntime.wrap(function _callee11$(_context20) { | ||
while (1) { | ||
switch (_context20.prev = _context20.next) { | ||
case 0: | ||
spy = jest.fn(); | ||
array = [Promise.resolve('foo'), Promise.resolve('bar'), 'baz']; | ||
_context20.t0 = expect; | ||
_context20.next = 5; | ||
return _.forArray.call(array, spy); | ||
case 5: | ||
_context20.t1 = _context20.sent; | ||
(0, _context20.t0)(_context20.t1).not.toBeDefined(); | ||
_context20.t2 = expect; | ||
_context20.next = 10; | ||
return spy.mock.calls; | ||
case 10: | ||
_context20.t3 = _context20.sent; | ||
_context20.t4 = [['foo', 0, array], ['bar', 1, array], ['baz', 2, array]]; | ||
(0, _context20.t2)(_context20.t3).toEqual(_context20.t4); | ||
case 13: | ||
case 'end': | ||
return _context20.stop(); | ||
} | ||
} | ||
}, _callee11, undefined); | ||
}))); | ||
}); | ||
// ------------------------------------------------------------------- | ||
describe('fromCallback()', function () { | ||
it('creates a promise which resolves with value passed to the callback', _asyncToGenerator(regeneratorRuntime.mark(function _callee12() { | ||
return regeneratorRuntime.wrap(function _callee12$(_context21) { | ||
while (1) { | ||
switch (_context21.prev = _context21.next) { | ||
case 0: | ||
_context21.t0 = expect; | ||
_context21.next = 3; | ||
return (0, _.fromCallback)(function (cb) { | ||
return cb(null, 'foo'); | ||
}); | ||
case 3: | ||
_context21.t1 = _context21.sent; | ||
(0, _context21.t0)(_context21.t1).toBe('foo'); | ||
case 5: | ||
case 'end': | ||
return _context21.stop(); | ||
} | ||
} | ||
}, _callee12, undefined); | ||
}))); | ||
it('creates a promise which rejects with reason passed to the callback', _asyncToGenerator(regeneratorRuntime.mark(function _callee13() { | ||
return regeneratorRuntime.wrap(function _callee13$(_context22) { | ||
while (1) { | ||
switch (_context22.prev = _context22.next) { | ||
case 0: | ||
_context22.t0 = expect; | ||
_context22.next = 3; | ||
return rejectionOf((0, _.fromCallback)(function (cb) { | ||
return cb('bar'); | ||
})); | ||
case 3: | ||
_context22.t1 = _context22.sent; | ||
(0, _context22.t0)(_context22.t1).toBe('bar'); | ||
case 5: | ||
case 'end': | ||
return _context22.stop(); | ||
} | ||
} | ||
}, _callee13, undefined); | ||
}))); | ||
}); | ||
// ------------------------------------------------------------------- | ||
describe('join()', function () { | ||
it('calls the callback once promises are resolved', function () { | ||
return (0, _.join)(Promise.resolve('foo'), Promise.resolve('bar'), function (foo, bar) { | ||
expect(foo).toBe('foo'); | ||
expect(bar).toBe('bar'); | ||
}); | ||
}); | ||
it('can takes inputs in an array', function () { | ||
return (0, _.join)([Promise.resolve('foo'), Promise.resolve('bar')], function (foo, bar) { | ||
expect(foo).toBe('foo'); | ||
expect(bar).toBe('bar'); | ||
}); | ||
}); | ||
it('rejects if one promise rejects', _asyncToGenerator(regeneratorRuntime.mark(function _callee14() { | ||
return regeneratorRuntime.wrap(function _callee14$(_context23) { | ||
while (1) { | ||
switch (_context23.prev = _context23.next) { | ||
case 0: | ||
_context23.t0 = expect; | ||
_context23.next = 3; | ||
return rejectionOf((0, _.join)(Promise.resolve('foo'), reject('bar'), function (foo, bar) { | ||
expect(foo).toBe('foo'); | ||
expect(bar).toBe('bar'); | ||
})); | ||
case 3: | ||
_context23.t1 = _context23.sent; | ||
(0, _context23.t0)(_context23.t1).toBe('bar'); | ||
case 5: | ||
case 'end': | ||
return _context23.stop(); | ||
} | ||
} | ||
}, _callee14, undefined); | ||
}))); | ||
}); | ||
// ------------------------------------------------------------------- | ||
describe('lastly()', function () { | ||
it('calls a callback on resolution', _asyncToGenerator(regeneratorRuntime.mark(function _callee15() { | ||
var _context24; | ||
var value, spy; | ||
return regeneratorRuntime.wrap(function _callee15$(_context25) { | ||
while (1) { | ||
switch (_context25.prev = _context25.next) { | ||
case 0: | ||
value = {}; | ||
spy = jest.fn(); | ||
_context25.t0 = expect; | ||
_context25.next = 5; | ||
return (_context24 = Promise.resolve(value), _.lastly).call(_context24, spy); | ||
case 5: | ||
_context25.t1 = _context25.sent; | ||
_context25.t2 = value; | ||
(0, _context25.t0)(_context25.t1).toBe(_context25.t2); | ||
expect(spy).toHaveBeenCalledTimes(1); | ||
case 9: | ||
case 'end': | ||
return _context25.stop(); | ||
} | ||
} | ||
}, _callee15, undefined); | ||
}))); | ||
it('calls a callback on rejection', _asyncToGenerator(regeneratorRuntime.mark(function _callee16() { | ||
var _context26; | ||
var reason, spy; | ||
return regeneratorRuntime.wrap(function _callee16$(_context27) { | ||
while (1) { | ||
switch (_context27.prev = _context27.next) { | ||
case 0: | ||
reason = {}; | ||
spy = jest.fn(); | ||
_context27.t0 = expect; | ||
_context27.next = 5; | ||
return rejectionOf((_context26 = Promise.reject(reason), _.lastly).call(_context26, spy)); | ||
case 5: | ||
_context27.t1 = _context27.sent; | ||
_context27.t2 = reason; | ||
(0, _context27.t0)(_context27.t1).toBe(_context27.t2); | ||
expect(spy).toHaveBeenCalledTimes(1); | ||
case 9: | ||
case 'end': | ||
return _context27.stop(); | ||
} | ||
} | ||
}, _callee16, undefined); | ||
}))); | ||
}); | ||
// ------------------------------------------------------------------- | ||
describe('promisifyAll()', function () { | ||
it('returns a new object', function () { | ||
var o = {}; | ||
var r = (0, _.promisifyAll)(o); | ||
expect(typeof r).toBe('object'); | ||
expect(r).not.toBe(o); | ||
}); | ||
it('creates promisified version of all functions bound to the original object', _asyncToGenerator(regeneratorRuntime.mark(function _callee17() { | ||
var o, r; | ||
return regeneratorRuntime.wrap(function _callee17$(_context28) { | ||
while (1) { | ||
switch (_context28.prev = _context28.next) { | ||
case 0: | ||
o = { | ||
foo(cb) { | ||
cb(null, this); | ||
} | ||
}; | ||
r = (0, _.promisifyAll)(o); | ||
_context28.t0 = expect; | ||
_context28.next = 5; | ||
return r.foo(); | ||
case 5: | ||
_context28.t1 = _context28.sent; | ||
_context28.t2 = o; | ||
(0, _context28.t0)(_context28.t1).toBe(_context28.t2); | ||
case 8: | ||
case 'end': | ||
return _context28.stop(); | ||
} | ||
} | ||
}, _callee17, undefined); | ||
}))); | ||
it('ignores functions ending with Sync or Async', function () { | ||
var o = { | ||
fooAsync() {}, | ||
fooSync() {} | ||
}; | ||
var r = _.promisifyAll.call(o); | ||
expect(r.foo).not.toBeDefined(); | ||
expect(r.fooASync).not.toBeDefined(); | ||
expect(r.fooSync).not.toBeDefined(); | ||
}); | ||
}); | ||
// ------------------------------------------------------------------- | ||
describe('settle()', function () { | ||
it('works with arrays', function () { | ||
var _context29; | ||
return (_context29 = [Promise.resolve(42), Math.PI, reject('fatality')], _.settle).call(_context29).then(function (_ref18) { | ||
var _ref19 = _slicedToArray(_ref18, 3), | ||
status1 = _ref19[0], | ||
status2 = _ref19[1], | ||
status3 = _ref19[2]; | ||
expect(status1.isFulfilled()).toBe(true); | ||
expect(status2.isFulfilled()).toBe(true); | ||
expect(status3.isFulfilled()).toBe(false); | ||
// Alias. | ||
expect(status1.isResolved()).toBe(true); | ||
expect(status2.isResolved()).toBe(true); | ||
expect(status3.isResolved()).toBe(false); | ||
expect(status1.isRejected()).toBe(false); | ||
expect(status2.isRejected()).toBe(false); | ||
expect(status3.isRejected()).toBe(true); | ||
expect(status1.value()).toBe(42); | ||
expect(status2.value()).toBe(Math.PI); | ||
expect(status3.value.bind(status3)).toThrow(); | ||
expect(status1.reason.bind(status1)).toThrow(); | ||
expect(status2.reason.bind(status2)).toThrow(); | ||
expect(status3.reason()).toBe('fatality'); | ||
}); | ||
}); | ||
it('works with objects', function () { | ||
var _context30; | ||
return (_context30 = { | ||
a: Promise.resolve(42), | ||
b: Math.PI, | ||
c: reject('fatality') | ||
}, _.settle).call(_context30).then(function (_ref20) { | ||
var status1 = _ref20.a, | ||
status2 = _ref20.b, | ||
status3 = _ref20.c; | ||
expect(status1.isFulfilled()).toBe(true); | ||
expect(status2.isFulfilled()).toBe(true); | ||
expect(status3.isFulfilled()).toBe(false); | ||
// Alias. | ||
expect(status1.isResolved()).toBe(true); | ||
expect(status2.isResolved()).toBe(true); | ||
expect(status3.isResolved()).toBe(false); | ||
expect(status1.isRejected()).toBe(false); | ||
expect(status2.isRejected()).toBe(false); | ||
expect(status3.isRejected()).toBe(true); | ||
expect(status1.value()).toBe(42); | ||
expect(status2.value()).toBe(Math.PI); | ||
expect(status3.value.bind(status3)).toThrow(); | ||
expect(status1.reason.bind(status1)).toThrow(); | ||
expect(status2.reason.bind(status2)).toThrow(); | ||
expect(status3.reason()).toBe('fatality'); | ||
}); | ||
}); | ||
}); | ||
// ------------------------------------------------------------------- | ||
describe('tap(cb)', function () { | ||
it('call cb with the resolved value', function () { | ||
return new Promise(function (resolve) { | ||
var _context31; | ||
(_context31 = Promise.resolve('value'), _.tap).call(_context31, function (value) { | ||
expect(value).toBe('value'); | ||
resolve(); | ||
}); | ||
}); | ||
}); | ||
it('does not call cb if the promise is rejected', _asyncToGenerator(regeneratorRuntime.mark(function _callee18() { | ||
var _context32; | ||
return regeneratorRuntime.wrap(function _callee18$(_context33) { | ||
while (1) { | ||
switch (_context33.prev = _context33.next) { | ||
case 0: | ||
_context33.t0 = expect; | ||
_context33.next = 3; | ||
return rejectionOf((_context32 = reject('reason'), _.tap).call(_context32, function () { | ||
return reject('other reason'); | ||
})); | ||
case 3: | ||
_context33.t1 = _context33.sent; | ||
(0, _context33.t0)(_context33.t1).toBe('reason'); | ||
case 5: | ||
case 'end': | ||
return _context33.stop(); | ||
} | ||
} | ||
}, _callee18, undefined); | ||
}))); | ||
it('forwards the resolved value', _asyncToGenerator(regeneratorRuntime.mark(function _callee19() { | ||
var _context34; | ||
return regeneratorRuntime.wrap(function _callee19$(_context35) { | ||
while (1) { | ||
switch (_context35.prev = _context35.next) { | ||
case 0: | ||
_context35.t0 = expect; | ||
_context35.next = 3; | ||
return (_context34 = Promise.resolve('value'), _.tap).call(_context34, function () { | ||
return 'other value'; | ||
}); | ||
case 3: | ||
_context35.t1 = _context35.sent; | ||
(0, _context35.t0)(_context35.t1).toBe('value'); | ||
case 5: | ||
case 'end': | ||
return _context35.stop(); | ||
} | ||
} | ||
}, _callee19, undefined); | ||
}))); | ||
it('rejects if cb rejects', _asyncToGenerator(regeneratorRuntime.mark(function _callee20() { | ||
var _context36; | ||
return regeneratorRuntime.wrap(function _callee20$(_context37) { | ||
while (1) { | ||
switch (_context37.prev = _context37.next) { | ||
case 0: | ||
_context37.t0 = expect; | ||
_context37.next = 3; | ||
return rejectionOf((_context36 = Promise.resolve('value'), _.tap).call(_context36, function () { | ||
return reject('reason'); | ||
})); | ||
case 3: | ||
_context37.t1 = _context37.sent; | ||
(0, _context37.t0)(_context37.t1).toBe('reason'); | ||
case 5: | ||
case 'end': | ||
return _context37.stop(); | ||
} | ||
} | ||
}, _callee20, undefined); | ||
}))); | ||
}); | ||
describe('tap(null, cb)', function () { | ||
it('call cb with the rejected reason', function () { | ||
return new Promise(function (resolve) { | ||
var _context38; | ||
(_context38 = reject('reason'), _.tap).call(_context38, null, function (reason) { | ||
expect(reason).toBe('reason'); | ||
resolve(); | ||
}).catch(function () {}); // prevents the unhandled rejection warning | ||
}); | ||
}); | ||
it('does not call cb if the promise is resolved', _asyncToGenerator(regeneratorRuntime.mark(function _callee21() { | ||
var _context39; | ||
return regeneratorRuntime.wrap(function _callee21$(_context40) { | ||
while (1) { | ||
switch (_context40.prev = _context40.next) { | ||
case 0: | ||
_context40.t0 = expect; | ||
_context40.next = 3; | ||
return (_context39 = Promise.resolve('value'), _.tap).call(_context39, null, function () { | ||
return reject('other reason'); | ||
}); | ||
case 3: | ||
_context40.t1 = _context40.sent; | ||
(0, _context40.t0)(_context40.t1).toBe('value'); | ||
case 5: | ||
case 'end': | ||
return _context40.stop(); | ||
} | ||
} | ||
}, _callee21, undefined); | ||
}))); | ||
it('forwards the rejected reason', _asyncToGenerator(regeneratorRuntime.mark(function _callee22() { | ||
var _context41; | ||
return regeneratorRuntime.wrap(function _callee22$(_context42) { | ||
while (1) { | ||
switch (_context42.prev = _context42.next) { | ||
case 0: | ||
_context42.t0 = expect; | ||
_context42.next = 3; | ||
return rejectionOf((_context41 = reject('reason'), _.tap).call(_context41, null, function () { | ||
return 'value'; | ||
})); | ||
case 3: | ||
_context42.t1 = _context42.sent; | ||
(0, _context42.t0)(_context42.t1).toBe('reason'); | ||
case 5: | ||
case 'end': | ||
return _context42.stop(); | ||
} | ||
} | ||
}, _callee22, undefined); | ||
}))); | ||
it('rejects if cb rejects', _asyncToGenerator(regeneratorRuntime.mark(function _callee23() { | ||
var _context43; | ||
return regeneratorRuntime.wrap(function _callee23$(_context44) { | ||
while (1) { | ||
switch (_context44.prev = _context44.next) { | ||
case 0: | ||
_context44.t0 = expect; | ||
_context44.next = 3; | ||
return rejectionOf((_context43 = reject('reason'), _.tap).call(_context43, null, function () { | ||
return reject('other reason'); | ||
})); | ||
case 3: | ||
_context44.t1 = _context44.sent; | ||
(0, _context44.t0)(_context44.t1).toBe('other reason'); | ||
case 5: | ||
case 'end': | ||
return _context44.stop(); | ||
} | ||
} | ||
}, _callee23, undefined); | ||
}))); | ||
}); | ||
// ------------------------------------------------------------------- | ||
describe('timeout()', function () { | ||
var neverSettle = new Promise(function () {}); | ||
it('rejects a promise if not settled after a delay', _asyncToGenerator(regeneratorRuntime.mark(function _callee24() { | ||
return regeneratorRuntime.wrap(function _callee24$(_context45) { | ||
while (1) { | ||
switch (_context45.prev = _context45.next) { | ||
case 0: | ||
_context45.t0 = expect; | ||
_context45.next = 3; | ||
return rejectionOf(_.timeout.call(neverSettle, 10)); | ||
case 3: | ||
_context45.t1 = _context45.sent; | ||
_context45.t2 = _.TimeoutError; | ||
(0, _context45.t0)(_context45.t1).toBeInstanceOf(_context45.t2); | ||
case 6: | ||
case 'end': | ||
return _context45.stop(); | ||
} | ||
} | ||
}, _callee24, undefined); | ||
}))); | ||
it('call the callback if not settled after a delay', _asyncToGenerator(regeneratorRuntime.mark(function _callee25() { | ||
return regeneratorRuntime.wrap(function _callee25$(_context46) { | ||
while (1) { | ||
switch (_context46.prev = _context46.next) { | ||
case 0: | ||
_context46.t0 = expect; | ||
_context46.next = 3; | ||
return _.timeout.call(neverSettle, 10, function () { | ||
return 'bar'; | ||
}); | ||
case 3: | ||
_context46.t1 = _context46.sent; | ||
(0, _context46.t0)(_context46.t1).toBe('bar'); | ||
case 5: | ||
case 'end': | ||
return _context46.stop(); | ||
} | ||
} | ||
}, _callee25, undefined); | ||
}))); | ||
it('forwards the settlement if settled before a delay', _asyncToGenerator(regeneratorRuntime.mark(function _callee26() { | ||
var _context47; | ||
return regeneratorRuntime.wrap(function _callee26$(_context48) { | ||
while (1) { | ||
switch (_context48.prev = _context48.next) { | ||
case 0: | ||
_context48.t0 = expect; | ||
_context48.next = 3; | ||
return (_context47 = Promise.resolve('value'), _.timeout).call(_context47, 10); | ||
case 3: | ||
_context48.t1 = _context48.sent; | ||
(0, _context48.t0)(_context48.t1).toBe('value'); | ||
_context48.t2 = expect; | ||
_context48.next = 8; | ||
return rejectionOf((_context47 = reject('reason'), _.timeout).call(_context47, 10)); | ||
case 8: | ||
_context48.t3 = _context48.sent; | ||
(0, _context48.t2)(_context48.t3).toBe('reason'); | ||
case 10: | ||
case 'end': | ||
return _context48.stop(); | ||
} | ||
} | ||
}, _callee26, undefined); | ||
}))); | ||
it('rejects if cb throws synchronously', _asyncToGenerator(regeneratorRuntime.mark(function _callee27() { | ||
return regeneratorRuntime.wrap(function _callee27$(_context49) { | ||
while (1) { | ||
switch (_context49.prev = _context49.next) { | ||
case 0: | ||
_context49.t0 = expect; | ||
_context49.next = 3; | ||
return rejectionOf(_.timeout.call(neverSettle, 10, function () { | ||
throw 'reason'; // eslint-disable-line no-throw-literal | ||
})); | ||
case 3: | ||
_context49.t1 = _context49.sent; | ||
(0, _context49.t0)(_context49.t1).toBe('reason'); | ||
case 5: | ||
case 'end': | ||
return _context49.stop(); | ||
} | ||
} | ||
}, _callee27, undefined); | ||
}))); | ||
}); | ||
// ------------------------------------------------------------------- | ||
describe('unpromisify()', function () { | ||
it('forwards the result', function (done) { | ||
var fn = _.unpromisify.call(function () { | ||
return Promise.resolve('foo'); | ||
}); | ||
fn(function (error, result) { | ||
expect(error).toBe(null); | ||
expect(result).toBe('foo'); | ||
done(); | ||
}); | ||
}); | ||
it('forwards the error', function (done) { | ||
var fn = _.unpromisify.call(function () { | ||
return reject('foo'); | ||
}); | ||
fn(function (error) { | ||
expect(error).toBe('foo'); | ||
done(); | ||
}); | ||
}); | ||
}); | ||
//# sourceMappingURL=index.spec.js.map |
{ | ||
"name": "promise-toolbox", | ||
"version": "0.8.0", | ||
"version": "0.8.1", | ||
"license": "ISC", | ||
@@ -31,27 +31,27 @@ "description": "Essential utils for promises", | ||
"engines": { | ||
"node": ">=0.12" | ||
"node": ">=4" | ||
}, | ||
"dependencies": { | ||
"make-error": "^1.0.4" | ||
"make-error": "^1.2.2" | ||
}, | ||
"devDependencies": { | ||
"babel-cli": "^6.3.17", | ||
"babel-eslint": "^7.0.0", | ||
"babel-preset-babili": "^0.0.9", | ||
"babel-preset-latest": "^6.16.0", | ||
"babel-preset-stage-0": "^6.3.13", | ||
"dependency-check": "^2.5.1", | ||
"husky": "^0.12.0", | ||
"jest": "^18.1.0", | ||
"native-promise-only": "^0.8.1", | ||
"standard": "^8.0.0" | ||
"babel-cli": "^6.23.0", | ||
"babel-eslint": "^7.1.1", | ||
"babel-preset-env": "^1.1.10", | ||
"babel-preset-stage-0": "^6.22.0", | ||
"cross-env": "^3.1.4", | ||
"dependency-check": "^2.8.0", | ||
"husky": "^0.13.1", | ||
"jest": "^19.0.2", | ||
"rimraf": "^2.6.1", | ||
"standard": "^9.0.0" | ||
}, | ||
"scripts": { | ||
"build": "NODE_ENV=production babel --source-maps --out-dir=dist/ src/", | ||
"commit-msg": "npm test", | ||
"depcheck": "dependency-check ./package.json", | ||
"dev": "NODE_DEV=development babel --watch --source-maps --out-dir=dist/ src/", | ||
"build": "cross-env NODE_ENV=production babel --source-maps --out-dir=dist/ src/", | ||
"commitmsg": "npm test", | ||
"dev": "cross-env NODE_ENV=development babel --watch --source-maps --out-dir=dist/ src/", | ||
"dev-test": "jest --bail --watch", | ||
"lint": "standard", | ||
"posttest": "npm run lint && npm run depcheck", | ||
"posttest": "standard && dependency-check ./package.json", | ||
"prebuild": "rimraf dist/", | ||
"predev": "npm run prebuild", | ||
"prepublish": "npm run build", | ||
@@ -61,12 +61,12 @@ "test": "jest" | ||
"babel": { | ||
"env": { | ||
"production": { | ||
"comments": false, | ||
"presets": [ | ||
"babili" | ||
] | ||
} | ||
}, | ||
"presets": [ | ||
"latest", | ||
[ | ||
"env", | ||
{ | ||
"targets": { | ||
"browsers": "> 5%", | ||
"node": 4 | ||
} | ||
} | ||
], | ||
"stage-0" | ||
@@ -76,5 +76,6 @@ ] | ||
"jest": { | ||
"testPathDirs": [ | ||
"roots": [ | ||
"<rootDir>/src" | ||
] | ||
], | ||
"testRegex": "\\.spec\\.js$" | ||
}, | ||
@@ -81,0 +82,0 @@ "standard": { |
@@ -73,12 +73,16 @@ # promise-toolbox [![Build Status](https://travis-ci.org/JsCommunity/promise-toolbox.png?branch=master)](https://travis-ci.org/JsCommunity/promise-toolbox) | ||
// 1. | ||
if (token.requested) { | ||
console.log('cancellation has been requested') | ||
if (token.reason) { | ||
console.log('cancellation has been requested', token.reason.message) | ||
} | ||
// 2. | ||
token.throwIfRequested() | ||
try { | ||
token.throwIfRequested() | ||
} catch (reason) { | ||
console.log('cancellation has been requested', reason.message) | ||
} | ||
// 3. | ||
token.promise.then(() => { | ||
console.log('cancellation has been requested') | ||
token.promise.then(reason => { | ||
console.log('cancellation has been requested', reason.message) | ||
}) | ||
@@ -98,2 +102,13 @@ | ||
#### Combining cancel tokens | ||
> Create a token which is cancelled as soon as one token amongst many | ||
> is. | ||
```js | ||
// `token` will be cancelled (synchronously) as soon as `token1` or | ||
// `token2` or token3` is, with the same reason. | ||
const token = CancelToken.race([ token1, token2, token3 ]) | ||
``` | ||
#### @cancellable decorator | ||
@@ -456,21 +471,18 @@ | ||
### Installing dependencies | ||
``` | ||
# Install dependencies | ||
> npm install | ||
``` | ||
### Compilation | ||
# Run the tests | ||
> npm test | ||
The sources files are watched and automatically recompiled on changes. | ||
``` | ||
# Continuously compile | ||
> npm run dev | ||
``` | ||
### Tests | ||
# Continuously run the tests | ||
> npm run dev-test | ||
# Build for production (automatically called by npm install) | ||
> npm run build | ||
``` | ||
> npm run test-dev | ||
``` | ||
@@ -477,0 +489,0 @@ ## Contributions |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
141913
1636
1
500
Updatedmake-error@^1.2.2