Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

promise-toolbox

Package Overview
Dependencies
Maintainers
2
Versions
43
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

promise-toolbox - npm Package Compare versions

Comparing version 0.4.0 to 0.5.0

17

dist/index.js

@@ -1,2 +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.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;} // ===================================================================
'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)');} // ===================================================================

@@ -32,3 +32,3 @@ 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 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;}return descriptor?(descriptor.value=newFn,descriptor):newFn;}; // -------------------------------------------------------------------
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

@@ -47,3 +47,3 @@ 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

// Usage: promise::delay(ms)
function delay(ms){return _wrap(this).then(function(value){return new Promise(function(resolve){setTimeout(function(){return resolve(value);},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

@@ -53,4 +53,4 @@ };};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); // -------------------------------------------------------------------

//
// fromCallback((cb) => fs.readFile('foo.txt', cb))
// .then((content) => {
// fromCallback(cb => fs.readFile('foo.txt', cb))
// .then(content => {
// console.log(content)

@@ -66,4 +66,4 @@ // })

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 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?this:_ref$context;_forIn(this,function(value,name){var newName=void 0;if(typeof value==='function'&&(newName=mapper(name,value,_this3))){target[newName]=promisify.call(value,context);}});return target;} // -------------------------------------------------------------------
function promisify(context){var fn=this;return _setFunctionNameAndLength(function(){var _this3=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||_this3,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 _this4=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,_this4))){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

@@ -87,6 +87,7 @@ // settled. Its fulfillment value is an object that implements the

function some(count){return _wrap(this).then(function(promises){return _some(promises,count);});} // -------------------------------------------------------------------
function tap(onResolved,onRejected){var _this5=this;var forward=function forward(){return _this5;};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)
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);});});} // -------------------------------------------------------------------
function timeout(ms){var _this7=this;return new Promise(function(resolve,reject){var handle=setTimeout(function(){handle=null;reject(new TimeoutError());if(typeof _this7.cancel==='function'){_this7.cancel();}},ms);_wrap(_this7).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

@@ -16,4 +16,5 @@ '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};} // ===================================================================

(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 _context14;return (0,_must2.default)((_context14=new Promise(function(){}),_.timeout).call(_context14,10)).to.reject.to.error(_.TimeoutError);});it('forwards the settlement if settled before a delay',function(){var _context15;return Promise.all([(0,_must2.default)((_context15=Promise.resolve('value'),_.timeout).call(_context15,10)).to.resolve.to.equal('value'),(0,_must2.default)((_context15=Promise.reject('reason'),_.timeout).call(_context15,10)).to.reject.to.equal('reason')]);});}); // -------------------------------------------------------------------
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('forwards the settlement if settled before a delay',function(){var _context23;return Promise.all([(0,_must2.default)((_context23=Promise.resolve('value'),_.timeout).call(_context23,10)).to.resolve.to.equal('value'),(0,_must2.default)((_context23=Promise.reject('reason'),_.timeout).call(_context23,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();});});});
//# sourceMappingURL=index.spec.js.map
{
"name": "promise-toolbox",
"version": "0.4.0",
"version": "0.5.0",
"license": "ISC",

@@ -42,3 +42,3 @@ "description": "Essential utils for promises",

"babel-preset-stage-0": "^6.3.13",
"clarify": "^1.0.5",
"clarify": "^2.0.0",
"dependency-check": "^2.5.1",

@@ -51,3 +51,3 @@ "julien-f-source-map-support": "0.0.0",

"sinon": "^1.17.2",
"standard": "^6.0.7",
"standard": "^7.0.0",
"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)

@@ -222,7 +222,7 @@ // → {

return a.b.c.d()
})::catchPlus(TypeError, ReferenceError, (reason) => {
})::catchPlus(TypeError, ReferenceError, reason => {
// Will end up here on programmer error
})::catchPlus(NetworkError, TimeoutError, (reason) => {
})::catchPlus(NetworkError, TimeoutError, reason => {
// Will end up here on expected everyday network errors
})::catchPlus((reason) => {
})::catchPlus(reason => {
// Catch any unexpected errors

@@ -259,3 +259,3 @@ })

Promise.resolve('bar'),
]::forEach((value) => {
]::forEach(value => {
console.log(value)

@@ -273,4 +273,4 @@ })

>
> The resolution value or rejection reason of the initial promise if
> forwarded.
> The resolution value or rejection reason of the initial promise is
> forwarded unless the callback rejects.

@@ -310,5 +310,5 @@ ```js

readFile(__filename).then((content) => console.log(content))
readFile(__filename).then(content => console.log(content))
fsPromise.readFile(__filename).then((content) => console.log(content))
fsPromise.readFile(__filename).then(content => console.log(content))
```

@@ -348,2 +348,24 @@

#### promise::tap(onResolved, onRejected)
> Like `.then()` but the original resolution/rejection is forwarded.
>
> Like `::lastly()`, if the callback rejects, it takes over the
> original resolution/rejection.
```js
import { tap } from 'promise-toolbox'
// Contrary to .then(), using ::tap() does not change the resolution
// value.
const promise1 = Promise.resolve(42)::tap(value => {
console.log(value)
})
// Like .then, the second param is used in case of rejection.
const promise2 = Promise.reject(42)::tap(null, reason => {
console.error(reason)
})
```
#### promise::timeout(ms)

@@ -350,0 +372,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc