Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

native promise/async support #1642

Closed
sibelius opened this issue Jul 21, 2023 · 3 comments · Fixed by #1644
Closed

native promise/async support #1642

sibelius opened this issue Jul 21, 2023 · 3 comments · Fixed by #1644

Comments

@sibelius
Copy link

What about adding native support to promise/async?

instead of adding another package https://github.com/mqttjs/async-mqtt

@robertsLando
Copy link
Member

This is already in my TODO list

@robertsLando
Copy link
Member

robertsLando commented Jul 24, 2023

@vishnureddy17 @BertKleewein What's the best approach for this in your opinion? Should I create an alias method foreach public method like publishAsync subscribeAsync etc... or should I add an override to actual functions? How would you expect the override to work?

I was tring adding an override to client.publish like this (see PR):

let toReturn: MqttClient | Promise<void> = this

if (typeof callback === 'function') {
	const deferred = new Deferred<void>()
	toReturn = deferred.promise
	callback = deferred.callback
}

where Deferred is an util class like:

export class Deferred<T> {
	private readonly _promise: Promise<T>

	private _resolve: (value?: T | PromiseLike<T>) => void

	private _reject: (reason?: any) => void

	constructor() {
		this._promise = new Promise<T>((resolve, reject) => {
			this._resolve = resolve
			this._reject = reject
		})
	}

	get promise(): Promise<T> {
		return this._promise
	}

	get callback(): GenericCallback<T> {
		return (error?: Error, result?: T): void => {
			if (error) {
				this.reject(error)
			} else {
				this.resolve(result)
			}
		}
	}

	resolve = (value?: T | PromiseLike<T>): void => {
		this._resolve(value)
	}

	reject = (reason?: any): void => {
		this._reject(reason)
	}
}

First problem with this is that if someone doesn't provide a function the method will always return a promise and that could be not expected, in fact many tests fail with that change. IMO the cleaner approach (at code side) is to create an alias method

@vishnureddy17
Copy link
Member

IMO the cleaner approach (at code side) is to create an alias method

I agree.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants