Backendless Support
 
Answered

Backendless v3 and Promises

hi there,

I'm having some problems understanding how I should handle Backendless in JS (Angular 4). I am running Backendless v3 for legacy reasons. If I explicitly set Backendless.enablePromises(); I do not seem to get this working, meaning that even a simple statement as: Backendless.UserService.register(user).then(userRegistered).catch(gotError);

gives me an error ('then' cannot be applied to object of type User). Any ideas why this is the case? I must be missing something simple.

If I disable promises, then I can use Async calls (for example Backendless.UserService.getCurrentUser(new Backendless.Async(success));), these work only if I do not call Backendless.enablePromises();, otherwise the async calls do not work either.

However, I'd like to use promises, any help is appreciated, thank you.

Leave a Comment

Comments (3)

photo
1

Hi Marco

Does this error come from TypeScript compiler?

If true, you need to specify that you are expecting Promise as result of Backendless.UserService.register(user)

try this one:

Backendless.UserService.register<Promise>(user).then(...)

please let us know if it helped for you.

Regards, Vlad

photo
1

thank you Vlad, I can now enable promises with:

Backendless.enablePromises();

and get it to work using:

Backendless.UserService.getCurrentUser<Promise<any>>()

.then(this.success)

.catch(this.error);

Previously I was using:

Backendless.UserService.getCurrentUser(new Backendless.Async(this.success, this.error, this));

How would you recommend passing the current context (this), so that I can use it when the promise resolves?

Thank you again for your help.

photo
1

there are a few solutions for keeping context

1) keep context in a variable (old-school)

  1. var self = this;
  2. Backendless.UserService.getCurrentUser<Promise<any>>()
  3. .then(function(result){
  4. self.success(result)
  5. })

2) use "Function.bind(context)" https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

  1. Backendless.UserService.getCurrentUser<Promise<any>>()
  2. .then(this.success.bind(this))

3) use ArrowFunctions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

  1. Backendless.UserService.getCurrentUser<Promise<any>>()
  2. .then(result => this.success(result))

photo