thenifiedly
Advanced tools
Comparing version 0.1.0 to 0.2.1
89
index.js
@@ -1,34 +0,69 @@ | ||
'use strict'; | ||
'use strict' | ||
function thenifiedApplier(thisArg, fn, args) { | ||
return function promiseHanlder(resolve, reject) { | ||
args.push(function callback(err, value) { | ||
if (err) { | ||
reject(err); | ||
} else { | ||
resolve(value); | ||
const defaultOptions = { | ||
mutipleValues: false, | ||
beginningError: true, | ||
promiseClass: Promise, | ||
} | ||
const handle = (applier, options) => | ||
options.mutipleValues | ||
? (args, resolve, reject) => { | ||
const { beginningError } = options | ||
applier((...cbArgs) => { | ||
let err | ||
if (beginningError && (err = cbArgs[0])) { | ||
reject(err) | ||
} else { | ||
resolve(beginningError ? cbArgs.slice(1) : cbArgs) | ||
} | ||
}, args) | ||
} | ||
}); | ||
fn.apply(thisArg, args); | ||
}; | ||
: options.beginningError | ||
? (args, resolve, reject) => { | ||
applier((err, val) => { | ||
if (err) { | ||
reject(err) | ||
} else { | ||
resolve(val) | ||
} | ||
}, args) | ||
} | ||
: (args, resolve) => { | ||
applier(resolve, args) | ||
} | ||
const factory = (applier, factoryOptions) => { | ||
const options = Object.assign({}, defaultOptions, factoryOptions) | ||
const P = options.promiseClass | ||
const handler = handle(applier, options) | ||
return (...args) => new P(handler.bind(null, args)) | ||
} | ||
module.exports = { | ||
call(func, ...args) { | ||
return new Promise(thenifiedApplier(null, func, args)); | ||
}, | ||
const call = factory((callback, [fn, ...args]) => { | ||
args.push(callback) | ||
fn.apply(undefined, args) | ||
}) | ||
callMethod(methodName, self, ...args) { | ||
return new Promise(thenifiedApplier(self, self[methodName], args)); | ||
const callMethod = factory((callback, [method, instance, ...args]) => { | ||
args.push(callback) | ||
instance[method].apply(instance, args) | ||
}) | ||
const tillEvent = factory( | ||
(callback, [event, emitter]) => { | ||
emitter.once(event, callback) | ||
}, | ||
{ beginningError: false } | ||
) | ||
callMethodFactory(methodName) { | ||
const functionName = | ||
'thenifiedlyCall' + methodName[0].toUpperCase() + methodName.slice(1); | ||
return { | ||
[functionName]: function(self, ...args) { | ||
return new Promise(thenifiedApplier(self, self[methodName], args)); | ||
} | ||
}[functionName]; | ||
} | ||
}; | ||
module.exports = { | ||
call, | ||
callMethod, | ||
tillEvent, | ||
factory, | ||
} |
{ | ||
"name": "thenifiedly", | ||
"version": "0.1.0", | ||
"version": "0.2.1", | ||
"description": "Call a callback style function with es6 promise returned.", | ||
"main": "thenifiedly.js", | ||
"author": { | ||
"name": "Patrick Liu", | ||
"email": "zeldalink0515@gmail.com", | ||
"url": "https://github.com/lrills" | ||
}, | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/lrills/thenifiedly" | ||
}, | ||
"files": [ | ||
"index.js" | ||
"index.js", | ||
"README.md" | ||
], | ||
@@ -13,9 +22,15 @@ "scripts": { | ||
"prettier": "prettier *.js **/*.js --write --single-quote", | ||
"prepublish": "npm test" | ||
"prepublishOnly": "npm test" | ||
}, | ||
"author": { | ||
"name": "Patrick Liu", | ||
"email": "zeldalink0515@gmail.com", | ||
"url": "https://github.com/lrills" | ||
}, | ||
"keywords": [ | ||
"promisify", | ||
"thenify", | ||
"promise", | ||
"then", | ||
"es6", | ||
"async", | ||
"await", | ||
"async-await", | ||
"callback" | ||
], | ||
"license": "MIT", | ||
@@ -26,6 +41,12 @@ "devDependencies": { | ||
"jest": "^23.5.0", | ||
"moxy": "https://github.com/lrills/moxy/releases/download/v0.1.0-5/moxy.tar.gz", | ||
"pify": "^4.0.0", | ||
"thenify": "^3.3.0", | ||
"thenify-all": "^1.6.0" | ||
}, | ||
"jest": { | ||
"setupFiles": [ | ||
"<rootDir>/node_modules/moxy/lib/extends/jest.js" | ||
] | ||
} | ||
} |
104
README.md
@@ -14,27 +14,27 @@ # thenifiedly | ||
```js | ||
import http from 'http'; | ||
import thenifiedly from 'thenifiedly'; | ||
import http from 'http' | ||
import thenifiedly from 'thenifiedly' | ||
const callWrite = thenifiedly.callMethodFactory('write'); | ||
const endRes = thenifiedly.callMethod.bind(null, 'end') | ||
http.createServer(async (req, res) => { | ||
const ghRes = await thenifiedly.call( | ||
const githubRes = await thenifiedly.call( | ||
http.get, | ||
'https://github.com' | ||
); | ||
await callWrite(res, `GitHub is ${ | ||
ghRes.statusCode < 300 ? 'ok': 'down' | ||
}! `); | ||
ghRes.destroy(); | ||
) | ||
await callMethod('end', res, 'Bye!'); | ||
console.log('Response Ended!'); | ||
}); | ||
await thenifiedly.callMethod('write', res, `GitHub is ${ | ||
githubRes.statusCode < 300 ? 'ok': 'down' | ||
}! `) | ||
await endRes(res, 'Bye!') | ||
console.log('Response Ended!') | ||
}) | ||
``` | ||
This is especially useful when the function/instance is from the parameters or returned dynamically. Thus you don't need to wrap it every time before use, and might gain small performance enhancement from it. Check [benchmark](#benchmark). | ||
This is especially useful when the function/instance to use comes from callback arguments or generated dynamically each time. So you don't need to wrap it every time before use, and might gain small performance enhancement from it. Check [benchmark](#benchmark). | ||
## API | ||
### call: (fn, [...args]) ⇒ `Promise` | ||
### call: (fn[, ...args]) ⇒ `Promise` | ||
Call a callback style function with postceding arguments, return a promise. | ||
@@ -50,7 +50,7 @@ | ||
async () => { | ||
const statOfMe = await thenifiedly.call(fs.stat, '/tmp/me'); | ||
const statOfMe = await thenifiedly.call(fs.stat, '/tmp/me') | ||
} | ||
``` | ||
### callMethod: (method, instance, [...args]) ⇒ `Promise` | ||
### callMethod: (method, instance[, ...args]) ⇒ `Promise` | ||
@@ -68,26 +68,68 @@ #### method `string|Symbol` | ||
async () => { | ||
const worker = child_process.fork('some.js'); | ||
await thenifiedly.callMethod('send', worker, { do: 'a job' }); | ||
const worker = child_process.fork('some.js') | ||
await thenifiedly.callMethod('send', worker, { do: 'a job' }) | ||
} | ||
``` | ||
### callMethodFactory: (method) ⇒ (instance, [...args]) ⇒ `Promise` | ||
Make a method calling function with the method name specified. | ||
### tillEvent: (event, emitter) ⇒ `Promise` | ||
Return a promise which resolves once the specified event fired by the emitter. | ||
#### method `string|Symbol` | ||
The method name to be called on the _instance_ object. | ||
#### event `string` | ||
The event name to be listened. | ||
#### instance `Object` | ||
The object contains the _method_ to be called. | ||
#### emitter `EventEmitter` | ||
A node _EventEmitter_ instance. | ||
#### args `any[]` | ||
Arguments to be passed to method, except the postceded callback function. | ||
```js | ||
async () => { | ||
await thenifiedly.tillEvent('connect', db) | ||
} | ||
``` | ||
### factory: (applier, options) ⇒ (...args) ⇒ `Promise` | ||
Factory function to generate promisify helper for any kind of callback function. | ||
#### applier: (callback, args) => void | ||
Function to make arrange of the callback function applying. | ||
##### callback: `Function` | ||
Callback created by factory, you should inject it while calling. | ||
##### args: `any[]` | ||
Parameters passed to your generated helper function when using. | ||
#### options `Object` | ||
##### options.mutipleValues `boolean` | ||
Whether multiple values passed to the callback, an array of values would be resolved instead if set to true. | ||
Default to `false`. | ||
##### options.beginningError `boolean` | ||
Whether callback arguments begins with the first arg as the error thrown. Default to `true`. | ||
##### options.promiseClass `boolean` | ||
The promise constructor to `new` the promise with. Default to native `Promise`. | ||
```js | ||
const callEnd = thenifiedly.callMethodFactory('end'); | ||
function sumUntilEach(cb, ...nums) { | ||
cb( | ||
...nums.reduce((arr, n) => { | ||
const len = arr.length | ||
const last = len === 0 ? 0 : arr[len - 1] | ||
return arr.concat(last + n) | ||
}, []) | ||
) | ||
} | ||
http.createServer(async (req, res) => { | ||
await callEnd(res, 'Hello world!'); | ||
console.log('Finished!'); | ||
}); | ||
const thenified = factory( | ||
(cb, args) => { | ||
sumUntilEach(cb, ...args) | ||
}, { | ||
mutipleValues: true, | ||
beginningError: false, | ||
promiseClass: MyPromise, | ||
}) | ||
await thenified(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) | ||
// [1, 3, 6, 10, 15, 21, 28, 36, 45, 55] | ||
``` | ||
@@ -94,0 +136,0 @@ |
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
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
No repository
Supply chain riskPackage does not have a linked source code repository. Without this field, a package will have no reference to the location of the source code use to generate the package.
Found 1 instance in 1 package
7293
58
169
0
7