NodeJs: util.promisify where the callback function has multiple arguments

You could make your own promisify, where you return a promise that resolves with the arguments of the callback and on the then block you destructure them. Hope this helps.

function awkwardFunction (options, data, callback) {
    // do stuff ...
    let item = "stuff message";
    return callback(null, data, item);
}

const mypromisify = (fn) =>
    (...args) =>
        new Promise(resolve =>
            fn(...args,
                (...a) => resolve(a)
            )
        );

const kptest = mypromisify(awkwardFunction);

kptest({ doIt: true }, 'some data')
    .then(([error, response, item]) => {
        console.log(response);
        console.log(item);
    })
    .catch(err => {
        console.log(err);
    });

It is not possible to have .then((response, item) => { because a promise represents single value. But you could have it like this .then(({response, item}) => { an object w/ two fields.

You'll need to provide a custom promisify implementation for the function.

const { promisify } = require('util')

awkwardFunction[promisify.custom] = (options, data) => new Promise((resolve, reject) => {
  awkwardFunction(options, data, (err, response, item) => {
    if(err) { reject(err) }
    else { resolve({ response, item }) }
  })
})

const kptest = promisify(awkwardFunction)

Or if this is the only place where the function is promisified you could use the promisified version directly const kptest = (options, data) => new Promise(... w/o additional promisification step.


util.promisify is intended to be used with Node-style callbacks with function (err, result): void signature.

Multiple arguments can be treated manually:

let kptest = require('util').promisify(
  (options, data, cb) => awkwardFunction(
    options,
    data,
    (err, ...results) => cb(err, results)
  )
)

kptest({doIt: true},'some data')
.then(([response, item]) => {...});

In case more sophisticated functionality is wanted, some third-party solution like pify can be used instead of util.promisify, it has multiArgs option to cover this case.

Tags:

Node.Js