promise-toolbox
Advanced tools
Comparing version 0.1.2 to 0.2.0
@@ -1,3 +0,3 @@ | ||
'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;exports.all=all;exports.asCallback=asCallback;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.timeout=timeout;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;} // =================================================================== | ||
var _toString=Object.prototype.toString;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(tag){return function(value){return _toString.call(value)===tag;};}(_toString.call([]));var _isFunction=function(tag){return function(value){return _toString.call(value)===tag;};}(_toString.call(_toString));var _isLength=function _isLength(value){return typeof value==='number'&&value>=0&&value<Infinity&&Math.floor(value)===value;};var _isArrayLike=function _isArrayLike(value){return value&&_isLength(value.length);};var _isIterable=typeof Symbol==='function'?function(value){return value&&_isFunction(value[Symbol.iterator]);}:function(){return false;};var _noop=function _noop(){}; // ------------------------------------------------------------------- | ||
'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.timeout=timeout;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;} // =================================================================== | ||
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&&_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=undefined;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. | ||
@@ -21,3 +21,3 @@ if(iteratee){_forEach(collection,function(item,key){result[key]=iteratee(item,key,collection);});}return result;}; // =================================================================== | ||
function asCallback(cb){ // cb can be undefined. | ||
if(cb){this.then(function(value){return cb(null,value);},function(error){return cb(error);}).catch(_noop);}return this;}exports.nodeify=asCallback; // ------------------------------------------------------------------- | ||
if(cb){this.then(function(value){return cb(null,value);},function(error){return cb(error);}).then(null,_noop);}return this;}exports.nodeify=asCallback; // ------------------------------------------------------------------- | ||
// Usage: | ||
@@ -33,5 +33,16 @@ // | ||
// } | ||
var cancellable=exports.cancellable=function cancellable(target,name,descriptor){var fn=descriptor?descriptor.value:target;function newFn(){var reject=undefined;var cancellation=new Promise(function(_,reject_){reject=reject_;});cancellation.catch(_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;}return descriptor?(descriptor.value=newFn,descriptor):newFn;}; // ------------------------------------------------------------------- | ||
var cancellable=exports.cancellable=function cancellable(target,name,descriptor){var fn=descriptor?descriptor.value:target;function newFn(){var reject=undefined;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;}return descriptor?(descriptor.value=newFn,descriptor):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=undefined;if(n<0||typeof (cb=arguments[n])!=='function'){return this;}var predicates=undefined;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=undefined,reject=undefined;var promise=new Promise(function(resolve_,reject_){resolve=resolve_;reject=reject_;});return {promise:promise,reject:reject,resolve:resolve};}; // ------------------------------------------------------------------- | ||
var defer=exports.defer=function defer(){var resolve=undefined,reject=undefined;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) | ||
@@ -43,4 +54,4 @@ function delay(ms){return _wrap(this).then(function(value){return new Promise(function(resolve){setTimeout(function(){return resolve(value);},ms);});});} // ------------------------------------------------------------------- | ||
// | ||
// fromCallback(cb => fs.readFile('foo.txt', cb)) | ||
// .then(content => { | ||
// fromCallback((cb) => fs.readFile('foo.txt', cb)) | ||
// .then((content) => { | ||
// console.log(content) | ||
@@ -55,5 +66,5 @@ // }) | ||
function lastly(cb){return _wrap(this).then(function(value){return _wrap(cb()).then(function(){return value;});},function(reason){return _wrap(cb()).then(function(){throw reason;});});}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([ thisArg ]) | ||
function promisify(thisArg){var fn=this;return _setFunctionNameAndLength(function(){var _this=this;var _arguments=arguments;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(thisArg||_this,args);});},fn.name,fn.length&&fn.length-1);} // Usage: obj::promisifyAll([ mapper ]) | ||
var DEFAULT_PALL_MAPPER=function DEFAULT_PALL_MAPPER(name,fn){return !(_endsWith(name,'Sync')||_endsWith(name,'Async'))&&name+'Async';};function promisifyAll(){var _this2=this;var mapper=arguments.length<=0||arguments[0]===undefined?DEFAULT_PALL_MAPPER:arguments[0];var result={};_forIn(this,function(value,name){var newName=undefined;if(typeof value==='function'&&(newName=mapper(name,value,_this2))){result[newName]=promisify.call(value,_this2);}});return result;} // ------------------------------------------------------------------- | ||
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 _this2=this;var _arguments=arguments;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||_this2,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 _this3=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?target:_ref$context;_forIn(this,function(value,name){var newName=undefined;if(typeof value==='function'&&(newName=mapper(name,value,_this3))){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 | ||
@@ -78,3 +89,3 @@ // settled. Its fulfillment value is an object that implements the | ||
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) | ||
function timeout(ms){var _this4=this;return new Promise(function(resolve,reject){var handle=setTimeout(function(){reject(new TimeoutError());if(_isFunction(_this4.cancel)){_this4.cancel();}},ms);_wrap(_this4).then(function(value){clearTimeout(handle);resolve(value);},function(reason){clearTimeout(handle);reject(reason);});});} | ||
function timeout(ms){var _this5=this;return new Promise(function(resolve,reject){var handle=setTimeout(function(){handle=null;reject(new TimeoutError());if(typeof _this5.cancel==='function'){_this5.cancel();}},ms);_wrap(_this5).then(function(value){handle!==null&&clearTimeout(handle);resolve(value);},function(reason){handle!==null&&clearTimeout(handle);reject(reason);});});} | ||
//# sourceMappingURL=index.js.map |
@@ -1,8 +0,14 @@ | ||
'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 _sinon=require('sinon');var _sinon2=_interopRequireDefault(_sinon);var _=require('./');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};} // =================================================================== | ||
'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('catchPlus',function(){var ident=function ident(value){return value;};it('catches errors matching a predicate',function(){var _context;var predicate=function predicate(reason){return reason==='foo';};return Promise.all([(0,_must2.default)((_context=Promise.reject('foo'),_.catchPlus).call(_context,predicate,ident)).to.resolve.to.equal('foo'),(0,_must2.default)((_context=Promise.reject('bar'),_.catchPlus).call(_context,predicate,ident)).to.reject.to.equal('bar')]);});it('catches errors matching a class',function(){var _context2;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)((_context2=Promise.reject(error),_.catchPlus).call(_context2,CustomError1,ident)).to.resolve.to.equal(error), // A parent. | ||
(0,_must2.default)((_context2=Promise.reject(error),_.catchPlus).call(_context2,Error,ident)).to.resolve.to.equal(error), // Another class. | ||
(0,_must2.default)((_context2=Promise.reject(error),_.catchPlus).call(_context2,CustomError2,ident)).to.reject.to.equal(error)]);});it('catches errors matching an object pattern',function(){var _context3;var predicate={foo:0};return Promise.all([(0,_must2.default)((_context3=Promise.reject({foo:0}),_.catchPlus).call(_context3,predicate,ident)).to.resolve.to.be.an.object(),(0,_must2.default)((_context3=Promise.reject({foo:1}),_.catchPlus).call(_context3,predicate,ident)).to.reject.to.be.an.object(),(0,_must2.default)((_context3=Promise.reject({bar:0}),_.catchPlus).call(_context3,predicate,ident)).to.reject.to.be.an.object()]);});it('does not catch programmer errors',function(){var _context4;return Promise.all([(0,_must2.default)((_context4=Promise.reject(new TypeError('')),_.catchPlus).call(_context4,ident)).to.reject.to.error(TypeError),(0,_must2.default)((_context4=Promise.reject(new SyntaxError('')),_.catchPlus).call(_context4,ident)).to.reject.to.error(SyntaxError), // Unless matches by a predicate. | ||
(0,_must2.default)((_context4=Promise.reject(new TypeError('')),_.catchPlus).call(_context4,TypeError,ident)).to.resolve.to.error(TypeError)]);});}); // ------------------------------------------------------------------- | ||
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 _context;var value={};var spy=_sinon2.default.spy();return (0,_must2.default)((_context=Promise.resolve(value),_.lastly).call(_context,spy)).to.resolve.to.equal(value).then(function(){(0,_must2.default)(spy.callCount).to.equal(1);});});it('calls a callback on rejection',function(){var _context2;var reason={};var spy=_sinon2.default.spy();return (0,_must2.default)((_context2=Promise.reject(reason),_.lastly).call(_context2,spy)).to.reject.to.equal(reason).then(function(){(0,_must2.default)(spy.callCount).to.equal(1);});});}); // ------------------------------------------------------------------- | ||
describe('settle()',function(){it('works with arrays',function(){var _context3;return (_context3=[Promise.resolve(42),Math.PI,Promise.reject('fatality')],_.settle).call(_context3).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 _context4;return (_context4={a:Promise.resolve(42),b:Math.PI,c:Promise.reject('fatality')},_.settle).call(_context4).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('lastly()',function(){it('calls a callback on resolution',function(){var _context5;var value={};var spy=_sinon2.default.spy();return (0,_must2.default)((_context5=Promise.resolve(value),_.lastly).call(_context5,spy)).to.resolve.to.equal(value).then(function(){(0,_must2.default)(spy.callCount).to.equal(1);});});it('calls a callback on rejection',function(){var _context6;var reason={};var spy=_sinon2.default.spy();return (0,_must2.default)((_context6=Promise.reject(reason),_.lastly).call(_context6,spy)).to.reject.to.equal(reason).then(function(){(0,_must2.default)(spy.callCount).to.equal(1);});});}); // ------------------------------------------------------------------- | ||
describe('settle()',function(){it('works with arrays',function(){var _context7;return (_context7=[Promise.resolve(42),Math.PI,Promise.reject('fatality')],_.settle).call(_context7).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 _context8;return (_context8={a:Promise.resolve(42),b:Math.PI,c:Promise.reject('fatality')},_.settle).call(_context8).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('timeout()',function(){it('rejects a promise if not settled after a delay',function(){var _context9;return (0,_must2.default)((_context9=new Promise(function(){}),_.timeout).call(_context9,10)).to.reject.to.error(_.TimeoutError);});it('forwards the settlement if settled before a delay',function(){var _context10;return Promise.all([(0,_must2.default)((_context10=Promise.resolve('value'),_.timeout).call(_context10,10)).to.resolve.to.equal('value'),(0,_must2.default)((_context10=Promise.reject('reason'),_.timeout).call(_context10,10)).to.reject.to.equal('reason')]);});}); | ||
//# sourceMappingURL=index.spec.js.map |
{ | ||
"name": "promise-toolbox", | ||
"version": "0.1.2", | ||
"version": "0.2.0", | ||
"license": "ISC", | ||
@@ -38,3 +38,3 @@ "description": "Essential utils for promises", | ||
"babel-cli": "^6.3.17", | ||
"babel-eslint": "^5.0.0-beta6", | ||
"babel-eslint": "^5.0.0", | ||
"babel-plugin-transform-runtime": "^6.3.13", | ||
@@ -51,3 +51,3 @@ "babel-preset-es2015": "^6.3.13", | ||
"source-map-support": "^0.4.0", | ||
"standard": "^5.4.1", | ||
"standard": "^6.0.7", | ||
"trace": "^2.0.1" | ||
@@ -54,0 +54,0 @@ }, |
@@ -82,3 +82,3 @@ # promise-toolbox [![Build Status](https://travis-ci.org/julien-f/js-promise-toolbox.png?branch=master)](https://travis-ci.org/julien-f/js-promise-toolbox) | ||
promise.then(value => { | ||
promise.then((value) => { | ||
console.log(value) | ||
@@ -90,3 +90,3 @@ }) | ||
#### fromCallback(cb => fn(arg1, ..., argn, cb)) | ||
#### fromCallback((cb) => fn(arg1, ..., argn, cb)) | ||
@@ -98,4 +98,4 @@ > Easiest and most efficient way to promisify a function call. | ||
fromCallback(cb => fs.readFile('foo.txt', cb)) | ||
.then(content => { | ||
fromCallback((cb) => fs.readFile('foo.txt', cb)) | ||
.then((content) => { | ||
console.log(content) | ||
@@ -141,3 +141,3 @@ }) | ||
promises::all().then(values => { | ||
promises::all().then((values) => { | ||
console.log(values) | ||
@@ -177,3 +177,3 @@ }) | ||
Promise.resolve('bar') | ||
]::all().then(value => { | ||
]::all().then((value) => { | ||
console.log(value) | ||
@@ -186,3 +186,3 @@ // → ['foo', 'bar'] | ||
bar: Promise.resolve('bar') | ||
}::all().then(value => { | ||
}::all().then((value) => { | ||
console.log(value) | ||
@@ -210,2 +210,23 @@ // → { | ||
#### promise::catchPlus(predicate, cb) | ||
> 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. | ||
```js | ||
somePromise.then(() => { | ||
return a.b.c.d() | ||
})::catchPlus(TypeError, ReferenceError, (reason) => { | ||
// Will end up here on programmer error | ||
})::catchPlus(NetworkError, TimeoutError, (reason) => { | ||
// Will end up here on expected everyday network errors | ||
})::catchPlus((reason) => { | ||
// Catch any unexpected errors | ||
}) | ||
``` | ||
#### promise::delay(ms) | ||
@@ -238,3 +259,3 @@ | ||
Promise.resolve('bar'), | ||
]::forEach(value => { | ||
]::forEach((value) => { | ||
console.log(value) | ||
@@ -271,3 +292,3 @@ }) | ||
#### fn::promisify([ thisArg ]) / obj::promisifyAll() | ||
#### fn::promisify([ context ]) / obj::promisifyAll() | ||
@@ -289,5 +310,5 @@ > Creates async functions taking node-style callbacks, create new ones | ||
readFile(__filename).then(content => console.log(content)) | ||
readFile(__filename).then((content) => console.log(content)) | ||
fsPromise.readFileAsync(__filename).then(content => console.log(content)) | ||
fsPromise.readFile(__filename).then((content) => console.log(content)) | ||
``` | ||
@@ -333,2 +354,4 @@ | ||
```js | ||
import { timeout } from 'promise-toolbox' | ||
await doLongOperation()::timeout(100) | ||
@@ -335,0 +358,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
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
72321
153
385
2