I’m trying to use util.promisify()
to transform a function that uses a callback so I can call it with async/await: https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original
So far I’ve been able to use it with functions that have the callback as the final parameter, as it expects. But I’m getting confused on how to use it when another item is the final parameter.
I have a function that structured like this:
myFunction = function(userID, company, callback, jwt) { .... return callback(null, results) }
Since the jwt
is the final parameter, how can I use promisify on this and still pass the jwt
? I’d rather not change the structure of the original function because other places are calling it as-is
Advertisement
Answer
You can create a new function wrapper around your function that only accepts arguments in a different order in order to move the callback last:
const wrapper = (userID, company, jwt, callback) => myFunction(userID, company, callback, jwt); const promisified = utils.promisify(wrapper);
For a more generic solution, you can use Lodash’s rearg
that will change the order of arguments based on the array you give it:
const wrapper = _.rearg(myFunction, [0, 1, 3, 2]); const promisified = utils.promisify(wrapper);