moscajs / aedes

Barebone MQTT broker that can run on any stream server, the node way
MIT License
1.79k stars 231 forks source link

Ways to promisify aedes-codebase friendly. #381

Open gnought opened 4 years ago

gnought commented 4 years ago

Please suggest preferable ways to make aedes-codebase be promise friendly?

mcollina commented 4 years ago

Every time there is a function that is user specified, we should wrap it in the following way:

const result = fn(done)
if (result && typeof result.then === 'function') {
  result.then(function (res) { done(null, res) }, done)
}

This might become more specific in certain cases, see https://github.com/fastify/fastify/blob/master/lib/wrapThenable.js for an example

robertsLando commented 4 years ago

what about create an helper executor? Something like:

async function runSafe(fn) {

if (fn) {
 return  typeof fn.then === 'function' ? await fn() : fn()
}

return null

}
mcollina commented 4 years ago

unfortunately it won't work. It cannot be an async function otherwise you can get into problems of handling errors.

robertsLando commented 4 years ago

@mcollina Should we handle errors even in functions given by users? For example authenticate ? Shouldn't that be handled by them?

mcollina commented 4 years ago

In order to be reliable, we need to handle the errors thrown by async functions as they are errors passed to the cb.

gnought commented 4 years ago

Lots of aedes codes are in callback-based, is it possible to switch to promise-based?

mcollina commented 4 years ago

That will slow down aedes significantly, as well as increasing memory load.