Created
June 18, 2019 16:24
-
-
Save 40thieves/0177786f00e9dd92d23ff4c970620253 to your computer and use it in GitHub Desktop.
Promisified variadic function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> function foo(arg1, arg2, arg3) { | |
if (arguments.length === 2) { | |
arg3 = arg2 | |
} | |
console.log('arg1', arg1) | |
console.log('arg2', arg2) | |
console.log('arg3', arg3) | |
} | |
undefined | |
> foo(1, 2, 3) | |
arg1 1 | |
arg2 2 | |
arg3 3 | |
undefined | |
> const {promisify} = require('util') | |
undefined | |
> promisify | |
{ [Function: promisify] custom: Symbol(util.promisify.custom) } | |
> const thing = promisify(foo) | |
undefined | |
> thing(1, 2, 3) | |
arg1 1 | |
arg2 2 | |
arg3 3 | |
Promise { | |
<pending>, | |
domain: | |
Domain { | |
domain: null, | |
_events: { error: [Function: debugDomainError] }, | |
_eventsCount: 1, | |
_maxListeners: undefined, | |
members: [] } } | |
> thing(1, 2) | |
arg1 1 | |
arg2 2 | |
arg3 (err, ...values) => { | |
if (err) { | |
promiseReject(promise, err); | |
} else if (argumentNames !== undefined && values.length > 1) { | |
const obj = {}; | |
for (var i = 0; i < argumentNames.length; i++) | |
obj[argumentNames[i]] = values[i]; | |
promiseResolve(promise, obj); | |
} else { | |
promiseResolve(promise, values[0]); | |
} | |
} | |
Promise { | |
<pending>, | |
domain: | |
Domain { | |
domain: null, | |
_events: { error: [Function: debugDomainError] }, | |
_eventsCount: 1, | |
_maxListeners: undefined, | |
members: [] } } | |
> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment