Search code examples
javascriptpromisebluebird

Is it better to place promises on the front end or back end?


I'm currently in the process of refactoring my code since there are some load time issues that are preventing my data from being loaded properly on production.

Just to establish a better habit, would you suggest to place promises on the backend, where my db calls are being made, or on the front end where said db methods are called and the results are returned? Does using both at the same time ever happen?


Solution

  • as always in tech its all about trade offs, one isn't better than another however since I spend most of my time working in angular I'll tell you how I would do it:

    I would write a service that takes a single value from an RXJS subscription, then unwrap it using a promise here is a firebase example:

      getValue(path: string): Promise<any> {
        var pathArr = path.split('/')
        var col = pathArr[0]
        var doc = pathArr[1]
        if (doc) {
          return new Promise((resolve) => {
            this.afs
              .collection(col)
              .doc(doc)
              .valueChanges()
              .pipe(take(1))
              .subscribe((val) => {
                resolve(val);
              });
          });
        } else {
          return new Promise((resolve) => {
            this.afs
              .collection(col)
              .valueChanges()
              .pipe(take(1))
              .subscribe((val) => {
                resolve(val);
              });
          });
        }
      }
    }
    

    then I would get the value of the promise by using the .then() function, Same firebase example:

    this.Database.getValue('Developers').then((val) => {
          var output = [];
          val.forEach((dev: any) => {
            //@ts-ignore
            output.push(dev.name);
          });
          output = output.filter((_val) => {
            return _val !== undefined;
          });
          this.options = output;
          this.filteredOptions = this.developerForm
            .get('applyTo')
            .valueChanges.pipe(
              startWith(''),
              map((value) => this._filter(value))
            );
        });
      }
    

    in short my vote goes to front end haha :)