promise-toolbox
Advanced tools
Comparing version 0.5.1 to 0.6.0
@@ -1,88 +0,2 @@ | ||
'use strict';Object.defineProperty(exports,"__esModule",{value:true});exports.TimeoutError=exports.finally=exports.fromCallback=exports.forOwn=exports.forIterable=exports.forIn=exports.forEach=exports.forArray=exports.makeAsyncIterator=exports.defer=exports.cancellable=exports.nodeify=exports.isPromise=undefined;var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj;}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol?"symbol":typeof obj;};exports.all=all;exports.asCallback=asCallback;exports.catchPlus=catchPlus;exports.delay=delay;exports.join=join;exports.lastly=lastly;exports.promisify=promisify;exports.promisifyAll=promisifyAll;exports.reflect=reflect;exports.settle=settle;exports.some=some;exports.tap=tap;exports.timeout=timeout;exports.unpromisify=unpromisify;var _makeError=require('make-error');function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}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;} // =================================================================== | ||
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?str.length:arguments[2];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 _isIterable=typeof Symbol==='function'?function(value){return value&&typeof value[Symbol.iterator]==='function';}:function(){return false;};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; // ------------------------------------------------------------------- | ||
// Usage: | ||
// | ||
// @cancellable | ||
// async fn (cancellation, other, args) { | ||
// cancellation.catch(() => { | ||
// // do stuff regarding the cancellation request. | ||
// }) | ||
// | ||
// // do other stuff. | ||
// } | ||
var cancellable=exports.cancellable=function cancellable(target,name,descriptor){var fn=descriptor?descriptor.value:target;function newFn(){var reject=void 0;var cancellation=new Promise(function(_,reject_){ // eslint-disable-line promise/param-names | ||
reject=reject_;});cancellation.then(null,_noop);for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}var promise=fn.call.apply(fn,[this,cancellation].concat(args));promise.cancel=reject;return promise;}if(descriptor){descriptor.value=newFn;return descriptor;}return newFn;}; // ------------------------------------------------------------------- | ||
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==='undefined'?'undefined':_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 _this=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 _this;});} // ------------------------------------------------------------------- | ||
// 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:promise,reject:reject,resolve:resolve};}; // ------------------------------------------------------------------- | ||
// Usage: promise::delay(ms) | ||
function delay(ms){var _this2=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(_this2);},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 _this3=this;return _wrap(this).then(function(value){return _wrap(cb()).then(function(){return _this3;});},function(reason){return _wrap(cb()).then(function(){return _this3;});});}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: fn::promisify([ context ]) | ||
function promisify(context){var fn=this;return _setFunctionNameAndLength(function(){var _this4=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||_this4,args);});},fn.name,fn.length&&fn.length-1);}var _DEFAULT_PALL_MAPPER=function _DEFAULT_PALL_MAPPER(name,fn){return !(_endsWith(name,'Sync')||_endsWith(name,'Async'))&&name;}; // Usage: obj::promisifyAll([ opts ]) | ||
function promisifyAll(){var _this5=this;var _ref=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];var _ref$mapper=_ref.mapper;var mapper=_ref$mapper===undefined?_DEFAULT_PALL_MAPPER:_ref$mapper;var _ref$target=_ref.target;var target=_ref$target===undefined?{}:_ref$target;var _ref$context=_ref.context;var context=_ref$context===undefined?this:_ref$context;_forIn(this,function(value,name){var newName=void 0;if(typeof value==='function'&&(newName=mapper(name,value,_this5))){target[newName]=promisify.call(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 _this6=this;var forward=function forward(){return _this6;};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,Object.getPrototypeOf(TimeoutError).call(this,'operation timed out'));}return TimeoutError;}(_makeError.BaseError); // Usage: promise::timeout(ms, cb) | ||
function timeout(ms,cb){var _this8=this;return new Promise(function(resolve,reject){var handle=setTimeout(function(){handle=null;if(typeof _this8.cancel==='function'){_this8.cancel();}if(cb){resolve(cb());}else {reject(new TimeoutError());}},ms);_wrap(_this8).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);} | ||
'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.cancellable=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};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 _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}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)}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<1/0&&Math.floor(a)===a},_isArrayLike=function _isArrayLike(a){return a&&'function'!=typeof a&&_isLength(a.length)},_isIterable='function'==typeof Symbol?function(a){return a&&'function'==typeof a[Symbol.iterator]}:function(){return!1},_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 cancellable=exports.cancellable=function cancellable(a,b,c){function d(){var h=void 0,j=new Promise(function(l,m){h=m});j.then(null,_noop);for(var _len=arguments.length,g=Array(_len),_key=0;_key<_len;_key++)g[_key]=arguments[_key];var k=e.call.apply(e,[this,j].concat(g));return k.cancel=h,k}var e=c?c.value:a;return c?(c.value=d,c):d};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 _this=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 _this})}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 _this2=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(_this2)},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 _this3=this;return _wrap(this).then(function(b){return _wrap(a()).then(function(){return _this3})},function(b){return _wrap(a()).then(function(){return _this3})})}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 _this4=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||_this4,d)})},a.name,a.length&&a.length-1)};var _DEFAULT_PALL_MAPPER=function _DEFAULT_PALL_MAPPER(a,b){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 _this5=this,c=function c(){return _this5};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 _this7=this;return new Promise(function(c,d){var e=setTimeout(function(){e=null,'function'==typeof _this7.cancel&&_this7.cancel(),b?c(b()):d(new TimeoutError)},a);_wrap(_this7).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)} | ||
//# sourceMappingURL=index.js.map |
@@ -1,19 +0,2 @@ | ||
'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");}};}(); /* eslint-env mocha */var _must=require('must');var _must2=_interopRequireDefault(_must);var _makeError=require('make-error');var _makeError2=_interopRequireDefault(_makeError);var _sinon=require('sinon');var _sinon2=_interopRequireDefault(_sinon);var _=require('./');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};} // =================================================================== | ||
describe('all()',function(){it('with array',function(){var _context;return (0,_must2.default)((_context=[Promise.resolve('foo'),'bar'],_.all).call(_context)).to.resolve.to.eql(['foo','bar']);});it('with object',function(){var _context2;return (0,_must2.default)((_context2={foo:Promise.resolve('foo'),bar:'bar'},_.all).call(_context2)).to.resolve.to.eql({foo:'foo',bar:'bar'});});it('resolve with empty collection',function(){var _context3;return (0,_must2.default)((_context3=[],_.all).call(_context3)).to.resolve.to.eql([]);});it('rejects first rejection',function(){var _context4;return (0,_must2.default)((_context4=['foo',Promise.reject('bar')],_.all).call(_context4)).to.reject.to.equal('bar');});it('rejects first rejection (even with pending promises)',function(){var _context5;return (0,_must2.default)((_context5=[new Promise(function(){}),Promise.reject('bar')],_.all).call(_context5)).to.reject.to.equal('bar');});}); // ------------------------------------------------------------------- | ||
describe('catchPlus',function(){var ident=function ident(value){return value;};it('catches errors matching a predicate',function(){var _context6;var predicate=function predicate(reason){return reason==='foo';};return Promise.all([(0,_must2.default)((_context6=Promise.reject('foo'),_.catchPlus).call(_context6,predicate,ident)).to.resolve.to.equal('foo'),(0,_must2.default)((_context6=Promise.reject('bar'),_.catchPlus).call(_context6,predicate,ident)).to.reject.to.equal('bar')]);});it('catches errors matching a class',function(){var _context7;var CustomError1=(0,_makeError2.default)('CustomError1');var CustomError2=(0,_makeError2.default)('CustomError2');var error=new CustomError1();return Promise.all([ // The class itself. | ||
(0,_must2.default)((_context7=Promise.reject(error),_.catchPlus).call(_context7,CustomError1,ident)).to.resolve.to.equal(error), // A parent. | ||
(0,_must2.default)((_context7=Promise.reject(error),_.catchPlus).call(_context7,Error,ident)).to.resolve.to.equal(error), // Another class. | ||
(0,_must2.default)((_context7=Promise.reject(error),_.catchPlus).call(_context7,CustomError2,ident)).to.reject.to.equal(error)]);});it('catches errors matching an object pattern',function(){var _context8;var predicate={foo:0};return Promise.all([(0,_must2.default)((_context8=Promise.reject({foo:0}),_.catchPlus).call(_context8,predicate,ident)).to.resolve.to.be.an.object(),(0,_must2.default)((_context8=Promise.reject({foo:1}),_.catchPlus).call(_context8,predicate,ident)).to.reject.to.be.an.object(),(0,_must2.default)((_context8=Promise.reject({bar:0}),_.catchPlus).call(_context8,predicate,ident)).to.reject.to.be.an.object()]);});it('does not catch programmer errors',function(){var _context9;return Promise.all([(0,_must2.default)((_context9=Promise.reject(new TypeError('')),_.catchPlus).call(_context9,ident)).to.reject.to.error(TypeError),(0,_must2.default)((_context9=Promise.reject(new SyntaxError('')),_.catchPlus).call(_context9,ident)).to.reject.to.error(SyntaxError), // Unless matches by a predicate. | ||
(0,_must2.default)((_context9=Promise.reject(new TypeError('')),_.catchPlus).call(_context9,TypeError,ident)).to.resolve.to.error(TypeError)]);});}); // ------------------------------------------------------------------- | ||
describe('forArray()',function(){it('iterates over an array of promises',function(){var spy=_sinon2.default.spy();var array=[Promise.resolve('foo'),Promise.resolve('bar'),'baz'];return (0,_must2.default)(_.forArray.call(array,spy)).to.resolve.to.undefined().then(function(){(0,_must2.default)(spy.args).to.eql([['foo',0,array],['bar',1,array],['baz',2,array]]);});});}); // ------------------------------------------------------------------- | ||
describe('fromCallback()',function(){it('creates a promise which resolves with value passed to the callback',function(){return (0,_must2.default)((0,_.fromCallback)(function(cb){cb(null,'foo');})).to.resolve.to.equal('foo');});it('creates a promise which rejects with reason passed to the callback',function(){return (0,_must2.default)((0,_.fromCallback)(function(cb){cb('bar');})).to.reject.to.equal('bar');});}); // ------------------------------------------------------------------- | ||
describe('join()',function(){it('calls the callback once promises are resolved',function(){return (0,_.join)(Promise.resolve('foo'),Promise.resolve('bar'),function(foo,bar){(0,_must2.default)(foo).to.equal('foo');(0,_must2.default)(bar).to.equal('bar');});});it('can takes inputs in an array',function(){return (0,_.join)([Promise.resolve('foo'),Promise.resolve('bar')],function(foo,bar){(0,_must2.default)(foo).to.equal('foo');(0,_must2.default)(bar).to.equal('bar');});});it('rejects if one promise rejects',function(){return (0,_must2.default)((0,_.join)(Promise.resolve('foo'),Promise.reject('bar'),function(foo,bar){(0,_must2.default)(foo).to.equal('foo');(0,_must2.default)(bar).to.equal('bar');})).to.reject.to.equal('bar');});}); // ------------------------------------------------------------------- | ||
describe('lastly()',function(){it('calls a callback on resolution',function(){var _context10;var value={};var spy=_sinon2.default.spy();return (0,_must2.default)((_context10=Promise.resolve(value),_.lastly).call(_context10,spy)).to.resolve.to.equal(value).then(function(){(0,_must2.default)(spy.callCount).to.equal(1);});});it('calls a callback on rejection',function(){var _context11;var reason={};var spy=_sinon2.default.spy();return (0,_must2.default)((_context11=Promise.reject(reason),_.lastly).call(_context11,spy)).to.reject.to.equal(reason).then(function(){(0,_must2.default)(spy.callCount).to.equal(1);});});}); // ------------------------------------------------------------------- | ||
describe('promisifyAll()',function(){it('returns a new object',function(){var o={};var r=_.promisifyAll.call(o);(0,_must2.default)(r).to.be.an.object();(0,_must2.default)(r).to.not.equal(o);});it('creates promisified version of all functions bound to the original object',function(){var o={foo:function foo(cb){cb(null,this);}};var r=_.promisifyAll.call(o);return (0,_must2.default)(r.foo()).to.resolve.to.equal(o);});it('ignores functions ending with Sync or Async',function(){var o={fooAsync:function fooAsync(){},fooSync:function fooSync(){}};var r=_.promisifyAll.call(o);(0,_must2.default)(r).to.not.have.property('foo');(0,_must2.default)(r).to.not.have.property('fooASync');(0,_must2.default)(r).to.not.have.property('fooSync');});}); // ------------------------------------------------------------------- | ||
describe('settle()',function(){it('works with arrays',function(){var _context12;return (_context12=[Promise.resolve(42),Math.PI,Promise.reject('fatality')],_.settle).call(_context12).then(function(_ref){var _ref2=_slicedToArray(_ref,3);var status1=_ref2[0];var status2=_ref2[1];var status3=_ref2[2];(0,_must2.default)(status1.isFulfilled()).to.equal(true);(0,_must2.default)(status2.isFulfilled()).to.equal(true);(0,_must2.default)(status3.isFulfilled()).to.equal(false); // Alias. | ||
(0,_must2.default)(status1.isResolved()).to.equal(true);(0,_must2.default)(status2.isResolved()).to.equal(true);(0,_must2.default)(status3.isResolved()).to.equal(false);(0,_must2.default)(status1.isRejected()).to.equal(false);(0,_must2.default)(status2.isRejected()).to.equal(false);(0,_must2.default)(status3.isRejected()).to.equal(true);(0,_must2.default)(status1.value()).to.equal(42);(0,_must2.default)(status2.value()).to.equal(Math.PI);(0,_must2.default)(status3.value.bind(status3)).to.throw();(0,_must2.default)(status1.reason.bind(status1)).to.throw();(0,_must2.default)(status2.reason.bind(status2)).to.throw();(0,_must2.default)(status3.reason()).to.equal('fatality');});});it('works with objects',function(){var _context13;return (_context13={a:Promise.resolve(42),b:Math.PI,c:Promise.reject('fatality')},_.settle).call(_context13).then(function(_ref3){var status1=_ref3.a;var status2=_ref3.b;var status3=_ref3.c;(0,_must2.default)(status1.isFulfilled()).to.equal(true);(0,_must2.default)(status2.isFulfilled()).to.equal(true);(0,_must2.default)(status3.isFulfilled()).to.equal(false); // Alias. | ||
(0,_must2.default)(status1.isResolved()).to.equal(true);(0,_must2.default)(status2.isResolved()).to.equal(true);(0,_must2.default)(status3.isResolved()).to.equal(false);(0,_must2.default)(status1.isRejected()).to.equal(false);(0,_must2.default)(status2.isRejected()).to.equal(false);(0,_must2.default)(status3.isRejected()).to.equal(true);(0,_must2.default)(status1.value()).to.equal(42);(0,_must2.default)(status2.value()).to.equal(Math.PI);(0,_must2.default)(status3.value.bind(status3)).to.throw();(0,_must2.default)(status1.reason.bind(status1)).to.throw();(0,_must2.default)(status2.reason.bind(status2)).to.throw();(0,_must2.default)(status3.reason()).to.equal('fatality');});});}); // ------------------------------------------------------------------- | ||
describe('tap(cb)',function(){it('call cb with the resolved value',function(){return new Promise(function(resolve){var _context14;(_context14=Promise.resolve('value'),_.tap).call(_context14,function(value){(0,_must2.default)(value).to.equal('value');resolve();});});});it('does not call cb if the promise is rejected',function(){var _context15;return (0,_must2.default)((_context15=Promise.reject('reason'),_.tap).call(_context15,function(){return Promise.reject('other reason');})).to.reject.to.equal('reason');});it('forwards the resolved value',function(){var _context16;return (0,_must2.default)((_context16=Promise.resolve('value'),_.tap).call(_context16,function(){return 'other value';})).to.resolve.to.equal('value');});it('rejects if cb rejects',function(){var _context17;return (0,_must2.default)((_context17=Promise.resolve('value'),_.tap).call(_context17,function(){return Promise.reject('reason');})).to.reject.to.equal('reason');});});describe('tap(null, cb)',function(){it('call cb with the rejected reason',function(){return new Promise(function(resolve){var _context18;(_context18=Promise.reject('reason'),_.tap).call(_context18,null,function(reason){(0,_must2.default)(reason).to.equal('reason');resolve();});});});it('does not call cb if the promise is resolved',function(){var _context19;return (0,_must2.default)((_context19=Promise.resolve('value'),_.tap).call(_context19,null,function(){return Promise.reject('other reason');})).to.resolve.to.equal('value');});it('forwards the rejected reason',function(){var _context20;return (0,_must2.default)((_context20=Promise.reject('reason'),_.tap).call(_context20,null,function(){return 'value';})).to.reject.to.equal('reason');});it('rejects if cb rejects',function(){var _context21;return (0,_must2.default)((_context21=Promise.reject('reason'),_.tap).call(_context21,null,function(){return Promise.reject('other reason');})).to.reject.to.equal('other reason');});}); // ------------------------------------------------------------------- | ||
describe('timeout()',function(){it('rejects a promise if not settled after a delay',function(){var _context22;return (0,_must2.default)((_context22=new Promise(function(){}),_.timeout).call(_context22,10)).to.reject.to.error(_.TimeoutError);});it('call the callback if not settled after a delay',function(){var _context23;return (0,_must2.default)((_context23=new Promise(function(){}),_.timeout).call(_context23,10,function(){return 'bar';})).to.resolve.to.equal('bar');});it('forwards the settlement if settled before a delay',function(){var _context24;return Promise.all([(0,_must2.default)((_context24=Promise.resolve('value'),_.timeout).call(_context24,10)).to.resolve.to.equal('value'),(0,_must2.default)((_context24=Promise.reject('reason'),_.timeout).call(_context24,10)).to.reject.to.equal('reason')]);});}); // ------------------------------------------------------------------- | ||
describe('unpromisify()',function(){it('forwards the result',function(done){var fn=_.unpromisify.call(function(){return Promise.resolve('foo');});fn(function(error,result){(0,_must2.default)(error).to.not.exist();(0,_must2.default)(result).to.equal('foo');done();});});it('forwards the error',function(done){var fn=_.unpromisify.call(function(){return Promise.reject('foo');});fn(function(error){(0,_must2.default)(error).to.equal('foo');done();});});}); | ||
'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')}}();var _must=require('must'),_must2=_interopRequireDefault(_must),_makeError=require('make-error'),_makeError2=_interopRequireDefault(_makeError),_sinon=require('sinon'),_sinon2=_interopRequireDefault(_sinon),_=require('./');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}describe('all()',function(){it('with array',function(){var _context;return(0,_must2.default)((_context=[Promise.resolve('foo'),'bar'],_.all).call(_context)).to.resolve.to.eql(['foo','bar'])}),it('with object',function(){var _context2;return(0,_must2.default)((_context2={foo:Promise.resolve('foo'),bar:'bar'},_.all).call(_context2)).to.resolve.to.eql({foo:'foo',bar:'bar'})}),it('resolve with empty collection',function(){var _context3;return(0,_must2.default)((_context3=[],_.all).call(_context3)).to.resolve.to.eql([])}),it('rejects first rejection',function(){var _context4;return(0,_must2.default)((_context4=['foo',Promise.reject('bar')],_.all).call(_context4)).to.reject.to.equal('bar')}),it('rejects first rejection (even with pending promises)',function(){var _context5;return(0,_must2.default)((_context5=[new Promise(function(){}),Promise.reject('bar')],_.all).call(_context5)).to.reject.to.equal('bar')})}),describe('catchPlus',function(){var a=function a(b){return b};it('catches errors matching a predicate',function(){var _context6,b=function b(c){return'foo'===c};return Promise.all([(0,_must2.default)((_context6=Promise.reject('foo'),_.catchPlus).call(_context6,b,a)).to.resolve.to.equal('foo'),(0,_must2.default)((_context6=Promise.reject('bar'),_.catchPlus).call(_context6,b,a)).to.reject.to.equal('bar')])}),it('catches errors matching a class',function(){var _context7,b=(0,_makeError2.default)('CustomError1'),c=(0,_makeError2.default)('CustomError2'),d=new b;return Promise.all([(0,_must2.default)((_context7=Promise.reject(d),_.catchPlus).call(_context7,b,a)).to.resolve.to.equal(d),(0,_must2.default)((_context7=Promise.reject(d),_.catchPlus).call(_context7,Error,a)).to.resolve.to.equal(d),(0,_must2.default)((_context7=Promise.reject(d),_.catchPlus).call(_context7,c,a)).to.reject.to.equal(d)])}),it('catches errors matching an object pattern',function(){var _context8,b={foo:0};return Promise.all([(0,_must2.default)((_context8=Promise.reject({foo:0}),_.catchPlus).call(_context8,b,a)).to.resolve.to.be.an.object(),(0,_must2.default)((_context8=Promise.reject({foo:1}),_.catchPlus).call(_context8,b,a)).to.reject.to.be.an.object(),(0,_must2.default)((_context8=Promise.reject({bar:0}),_.catchPlus).call(_context8,b,a)).to.reject.to.be.an.object()])}),it('does not catch programmer errors',function(){var _context9;return Promise.all([(0,_must2.default)((_context9=Promise.reject(new TypeError('')),_.catchPlus).call(_context9,a)).to.reject.to.error(TypeError),(0,_must2.default)((_context9=Promise.reject(new SyntaxError('')),_.catchPlus).call(_context9,a)).to.reject.to.error(SyntaxError),(0,_must2.default)((_context9=Promise.reject(new TypeError('')),_.catchPlus).call(_context9,TypeError,a)).to.resolve.to.error(TypeError)])})}),describe('forArray()',function(){it('iterates over an array of promises',function(){var a=_sinon2.default.spy(),b=[Promise.resolve('foo'),Promise.resolve('bar'),'baz'];return(0,_must2.default)(_.forArray.call(b,a)).to.resolve.to.undefined().then(function(){(0,_must2.default)(a.args).to.eql([['foo',0,b],['bar',1,b],['baz',2,b]])})})}),describe('fromCallback()',function(){it('creates a promise which resolves with value passed to the callback',function(){return(0,_must2.default)((0,_.fromCallback)(function(a){a(null,'foo')})).to.resolve.to.equal('foo')}),it('creates a promise which rejects with reason passed to the callback',function(){return(0,_must2.default)((0,_.fromCallback)(function(a){a('bar')})).to.reject.to.equal('bar')})}),describe('join()',function(){it('calls the callback once promises are resolved',function(){return(0,_.join)(Promise.resolve('foo'),Promise.resolve('bar'),function(a,b){(0,_must2.default)(a).to.equal('foo'),(0,_must2.default)(b).to.equal('bar')})}),it('can takes inputs in an array',function(){return(0,_.join)([Promise.resolve('foo'),Promise.resolve('bar')],function(a,b){(0,_must2.default)(a).to.equal('foo'),(0,_must2.default)(b).to.equal('bar')})}),it('rejects if one promise rejects',function(){return(0,_must2.default)((0,_.join)(Promise.resolve('foo'),Promise.reject('bar'),function(a,b){(0,_must2.default)(a).to.equal('foo'),(0,_must2.default)(b).to.equal('bar')})).to.reject.to.equal('bar')})}),describe('lastly()',function(){it('calls a callback on resolution',function(){var _context10,a={},b=_sinon2.default.spy();return(0,_must2.default)((_context10=Promise.resolve(a),_.lastly).call(_context10,b)).to.resolve.to.equal(a).then(function(){(0,_must2.default)(b.callCount).to.equal(1)})}),it('calls a callback on rejection',function(){var _context11,a={},b=_sinon2.default.spy();return(0,_must2.default)((_context11=Promise.reject(a),_.lastly).call(_context11,b)).to.reject.to.equal(a).then(function(){(0,_must2.default)(b.callCount).to.equal(1)})})}),describe('promisifyAll()',function(){it('returns a new object',function(){var a={},b=(0,_.promisifyAll)(a);(0,_must2.default)(b).to.be.an.object(),(0,_must2.default)(b).to.not.equal(a)}),it('creates promisified version of all functions bound to the original object',function(){var a={foo:function foo(c){c(null,this)}},b=(0,_.promisifyAll)(a);return(0,_must2.default)(b.foo()).to.resolve.to.equal(a)}),it('ignores functions ending with Sync or Async',function(){var a={fooAsync:function fooAsync(){},fooSync:function fooSync(){}},b=_.promisifyAll.call(a);(0,_must2.default)(b).to.not.have.property('foo'),(0,_must2.default)(b).to.not.have.property('fooASync'),(0,_must2.default)(b).to.not.have.property('fooSync')})}),describe('settle()',function(){it('works with arrays',function(){var _context12;return(_context12=[Promise.resolve(42),Math.PI,Promise.reject('fatality')],_.settle).call(_context12).then(function(_ref){var _ref2=_slicedToArray(_ref,3),a=_ref2[0],b=_ref2[1],c=_ref2[2];(0,_must2.default)(a.isFulfilled()).to.equal(!0),(0,_must2.default)(b.isFulfilled()).to.equal(!0),(0,_must2.default)(c.isFulfilled()).to.equal(!1),(0,_must2.default)(a.isResolved()).to.equal(!0),(0,_must2.default)(b.isResolved()).to.equal(!0),(0,_must2.default)(c.isResolved()).to.equal(!1),(0,_must2.default)(a.isRejected()).to.equal(!1),(0,_must2.default)(b.isRejected()).to.equal(!1),(0,_must2.default)(c.isRejected()).to.equal(!0),(0,_must2.default)(a.value()).to.equal(42),(0,_must2.default)(b.value()).to.equal(Math.PI),(0,_must2.default)(c.value.bind(c)).to.throw(),(0,_must2.default)(a.reason.bind(a)).to.throw(),(0,_must2.default)(b.reason.bind(b)).to.throw(),(0,_must2.default)(c.reason()).to.equal('fatality')})}),it('works with objects',function(){var _context13;return(_context13={a:Promise.resolve(42),b:Math.PI,c:Promise.reject('fatality')},_.settle).call(_context13).then(function(_ref3){var a=_ref3.a,b=_ref3.b,c=_ref3.c;(0,_must2.default)(a.isFulfilled()).to.equal(!0),(0,_must2.default)(b.isFulfilled()).to.equal(!0),(0,_must2.default)(c.isFulfilled()).to.equal(!1),(0,_must2.default)(a.isResolved()).to.equal(!0),(0,_must2.default)(b.isResolved()).to.equal(!0),(0,_must2.default)(c.isResolved()).to.equal(!1),(0,_must2.default)(a.isRejected()).to.equal(!1),(0,_must2.default)(b.isRejected()).to.equal(!1),(0,_must2.default)(c.isRejected()).to.equal(!0),(0,_must2.default)(a.value()).to.equal(42),(0,_must2.default)(b.value()).to.equal(Math.PI),(0,_must2.default)(c.value.bind(c)).to.throw(),(0,_must2.default)(a.reason.bind(a)).to.throw(),(0,_must2.default)(b.reason.bind(b)).to.throw(),(0,_must2.default)(c.reason()).to.equal('fatality')})})}),describe('tap(cb)',function(){it('call cb with the resolved value',function(){return new Promise(function(a){var _context14;(_context14=Promise.resolve('value'),_.tap).call(_context14,function(b){(0,_must2.default)(b).to.equal('value'),a()})})}),it('does not call cb if the promise is rejected',function(){var _context15;return(0,_must2.default)((_context15=Promise.reject('reason'),_.tap).call(_context15,function(){return Promise.reject('other reason')})).to.reject.to.equal('reason')}),it('forwards the resolved value',function(){var _context16;return(0,_must2.default)((_context16=Promise.resolve('value'),_.tap).call(_context16,function(){return'other value'})).to.resolve.to.equal('value')}),it('rejects if cb rejects',function(){var _context17;return(0,_must2.default)((_context17=Promise.resolve('value'),_.tap).call(_context17,function(){return Promise.reject('reason')})).to.reject.to.equal('reason')})}),describe('tap(null, cb)',function(){it('call cb with the rejected reason',function(){return new Promise(function(a){var _context18;(_context18=Promise.reject('reason'),_.tap).call(_context18,null,function(b){(0,_must2.default)(b).to.equal('reason'),a()})})}),it('does not call cb if the promise is resolved',function(){var _context19;return(0,_must2.default)((_context19=Promise.resolve('value'),_.tap).call(_context19,null,function(){return Promise.reject('other reason')})).to.resolve.to.equal('value')}),it('forwards the rejected reason',function(){var _context20;return(0,_must2.default)((_context20=Promise.reject('reason'),_.tap).call(_context20,null,function(){return'value'})).to.reject.to.equal('reason')}),it('rejects if cb rejects',function(){var _context21;return(0,_must2.default)((_context21=Promise.reject('reason'),_.tap).call(_context21,null,function(){return Promise.reject('other reason')})).to.reject.to.equal('other reason')})}),describe('timeout()',function(){it('rejects a promise if not settled after a delay',function(){var _context22;return(0,_must2.default)((_context22=new Promise(function(){}),_.timeout).call(_context22,10)).to.reject.to.error(_.TimeoutError)}),it('call the callback if not settled after a delay',function(){var _context23;return(0,_must2.default)((_context23=new Promise(function(){}),_.timeout).call(_context23,10,function(){return'bar'})).to.resolve.to.equal('bar')}),it('forwards the settlement if settled before a delay',function(){var _context24;return Promise.all([(0,_must2.default)((_context24=Promise.resolve('value'),_.timeout).call(_context24,10)).to.resolve.to.equal('value'),(0,_must2.default)((_context24=Promise.reject('reason'),_.timeout).call(_context24,10)).to.reject.to.equal('reason')])})}),describe('unpromisify()',function(){it('forwards the result',function(a){var b=_.unpromisify.call(function(){return Promise.resolve('foo')});b(function(c,d){(0,_must2.default)(c).to.not.exist(),(0,_must2.default)(d).to.equal('foo'),a()})}),it('forwards the error',function(a){var b=_.unpromisify.call(function(){return Promise.reject('foo')});b(function(c){(0,_must2.default)(c).to.equal('foo'),a()})})}); | ||
//# sourceMappingURL=index.spec.js.map |
{ | ||
"name": "promise-toolbox", | ||
"version": "0.5.1", | ||
"version": "0.6.0", | ||
"license": "ISC", | ||
@@ -38,8 +38,9 @@ "description": "Essential utils for promises", | ||
"babel-cli": "^6.3.17", | ||
"babel-eslint": "^6.0.0", | ||
"babel-plugin-transform-runtime": "^6.3.13", | ||
"babel-preset-es2015": "^6.3.13", | ||
"babel-eslint": "^7.0.0", | ||
"babel-preset-babili": "^0.0.5", | ||
"babel-preset-latest": "^6.16.0", | ||
"babel-preset-stage-0": "^6.3.13", | ||
"clarify": "^2.0.0", | ||
"dependency-check": "^2.5.1", | ||
"ghooks": "^1.3.2", | ||
"julien-f-source-map-support": "0.0.0", | ||
@@ -49,23 +50,41 @@ "mocha": "^3.0.0", | ||
"native-promise-only": "^0.8.1", | ||
"nyc": "^8.1.0", | ||
"sinon": "^1.17.2", | ||
"standard": "^7.0.0", | ||
"standard": "^8.0.0", | ||
"trace": "^2.0.1" | ||
}, | ||
"scripts": { | ||
"build": "babel --source-maps --out-dir=dist/ src/", | ||
"dev": "babel --watch --source-maps --out-dir=dist/ src/", | ||
"build": "NODE_ENV=production babel --source-maps --out-dir=dist/ src/", | ||
"depcheck": "dependency-check ./package.json", | ||
"dev": "NODE_DEV=development babel --watch --source-maps --out-dir=dist/ src/", | ||
"dev-test": "mocha --opts .mocha.opts --watch --reporter=min \"dist/**/*.spec.js\"", | ||
"lint": "standard", | ||
"depcheck": "dependency-check ./package.json", | ||
"posttest": "npm run lint && npm run depcheck", | ||
"prepublish": "npm run build", | ||
"test": "nyc mocha --opts .mocha.opts \"dist/**/*.spec.js\"" | ||
"test": "mocha --opts .mocha.opts \"dist/**/*.spec.js\"" | ||
}, | ||
"babel": { | ||
"env": { | ||
"production": { | ||
"comments": false, | ||
"presets": [ | ||
"babili" | ||
] | ||
} | ||
}, | ||
"presets": [ | ||
"latest", | ||
"stage-0" | ||
] | ||
}, | ||
"standard": { | ||
"ignore": [ | ||
"dist/**" | ||
"dist" | ||
], | ||
"parser": "babel-eslint" | ||
}, | ||
"config": { | ||
"ghooks": { | ||
"commit-msg": "npm test" | ||
} | ||
} | ||
} |
@@ -125,2 +125,24 @@ # promise-toolbox [![Build Status](https://travis-ci.org/JsCommunity/promise-toolbox.png?branch=master)](https://travis-ci.org/JsCommunity/promise-toolbox) | ||
#### promisify(fn, [ context ]) / promisifyAll(obj) | ||
> Creates async functions taking node-style callbacks, create new ones | ||
> returning promises. | ||
```js | ||
import fs from 'fs' | ||
import { promisify, promisifyAll } from 'promise-toolbox' | ||
// Promisify a single function. | ||
// | ||
// If possible, the function name is kept and the new length is set. | ||
const readFile = promisify(fs.readFile) | ||
// Or all functions (own or inherited) exposed on a object. | ||
const fsPromise = promisifyAll(fs) | ||
readFile(__filename).then(content => console.log(content)) | ||
fsPromise.readFile(__filename).then(content => console.log(content)) | ||
``` | ||
### Pseudo-methods | ||
@@ -285,24 +307,2 @@ | ||
#### fn::promisify([ context ]) / obj::promisifyAll() | ||
> Creates async functions taking node-style callbacks, create new ones | ||
> returning promises. | ||
```js | ||
import fs from 'fs' | ||
import { promisify, promisifyAll } from 'promise-toolbox' | ||
// Promisify a single function. | ||
// | ||
// If possible, the function name is kept and the new length is set. | ||
const readFile = fs.readFile::promisify() | ||
// Or all functions (own or inherited) exposed on a object. | ||
const fsPromise = fs::promisifyAll() | ||
readFile(__filename).then(content => console.log(content)) | ||
fsPromise.readFile(__filename).then(content => console.log(content)) | ||
``` | ||
#### promise::reflect() | ||
@@ -309,0 +309,0 @@ |
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
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
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
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
86849
83
3
1