skip to Main Content

found this piece of code which is actually working but eslint is complaining about the misused promise

this.subject$.pipe(delay(this.debounceTime || 0)).subscribe(async ({ entry, observer }) => {
            const target = entry.target as HTMLElement;
            const isStillVisible = await this.isVisible(target);

            isStillVisible ? this.visible.emit() : this.invisible.emit();
        });

ESLint: Promise returned in function argument where a void return was expected.(@typescript-eslint/no-misused-promises)

i need to refactor this function to get rid of the eslint error

tried asynchronous IIFE inside the callback

2

Answers


  1. An async function implicitly returns a promise. You can change your callback to the following and it should still behave the same way but get rid of the error you are getting.

    this.subject$.pipe(delay(this.debounceTime || 0)).subscribe(({ entry, observer }) => {
        const target = entry.target as HTMLElement;
        this.isVisible(target)
        .then(function(isStillVisible) {
            isStillVisible ? this.visible.emit() : this.invisible.emit();
        });
    });

    This way the callback you pass to subscribe no longer returns a promise.

    Login or Signup to reply.
  2. You can convert promises via from but as @Eddi commented (thanks!) this isn’t required for switchMap since this converts to an observable under the hood

    this.subject$.pipe(
      delay(this.debounceTime || 0),
      switchMap(({ entry, observer }) => {
        const target = entry.target as HTMLElement;
        return this.isVisible(target)
      })
    ).subscribe((isStillVisible) => {
      isStillVisible ? this.visible.emit() : this.invisible.emit();
    });
    

    I don’t think the order of the switchMap and delay matters but I’d check this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search