I am attempting to util.promisify
the bonjour npm package. This is the original use case described in the docs:
var bonjour = require('bonjour')()
// advertise an HTTP server on port 3000
bonjour.publish({ name: 'My Web Server', type: 'http', port: 3000 })
// browse for all http services
bonjour.find({ type: 'http' }, function (service) {
console.log('Found an HTTP server:', service)
})
And this will not exit - bonjour.find()
stays open looking for http servers.
I want to promisify this and successfully resolve the promise after scanning for servers. Something like:
var bonjour = require('bonjour')
const util = require('util');
// advertise an HTTP server on port 3000
bonjour().publish({ name: 'My Web Server', type: 'http', port: 3000 })
// promisify the 'find' function
const find = util.promisify(bonjour().find.bind(bonjour()));
(async () => {
try {
const content = await find({ type: 'http' });
console.log(content)
} catch (err) {
// It will always error, although, the value of 'err' is the correct content.
console.error('There was an error');
}
})();
As noted in the comments, it will always throw an error, even though the value of err
is the desired output.
The promisify'd process expects an exit code 0, which I suspect isn't happening since the process doesn't return. Is this the right assumption? Does anyone have any other insights or solutions to get my promise to not throw an error but return the value that is currently being thrown?
Thanks!
That's because the bonjour
callback does not comply with the Node.js callback signature (err, data) => {}
. Indeed, bonjour.find
's callback has the success value as first parameter. You could wrap it in a proxy function like this:
function findWrapper(options, func) {
function callback(data, err) {
func(err, data);
}
return bonjour().find(options, callback);
}
const find = util.promisify(findWrapper);