0

I developed through AngularJS many asynchronous functions with the same signature which is app.Domain.GenericModel.EntityBase (my generic model) This is a sample:

get(resource: string): ng.IPromise<app.Domain.GenericModel.EntityBase[]> {
            var self = this;
            var deferred = self.qService.defer();
            self.httpService.get(resource).then(function (result: any) {
                deferred.resolve(result.data);
            }, function (errors) {
                self.exception = new app.Exceptions.Model.Exception(errors.status, errors.statusText);
                deferred.reject(self.exception);
            });

            return deferred.promise;
        }

Then I tried to call some services which are similar to the previous one with chained promises.So, I got this error : "Type IPromise is not assignable to type IPromise, Type EntityBase is not assignable to type void"

   var self = this; 
    var promise = self.$q.when();
    promise = promise.then(() => {
                                            return self.EcritureService.get(critureToSave);
                                        }).then((compte: EntityBase) => {
                                            return self.CompteService.getSingle(Number(data.compte));
                                        }).then((EntityBase) => {
                                            currentAccount.montantCpt = currentAccount.montantCpt + montant;
                                            return self.CompteService.update(currentAccount:EntityBase);
                                        });

I search a lot for this dilemma and all I've got, an inconspicuous method to convert my functions' returns to the common pattern "IPromise" through Type assertion which mostly based on the compiler's deception or something like that. I didn't comprehend this trick if anyone else have an idea..could he clarify it no matter what it's efficient or not.

Ahmed Chebbi
  • 9
  • 1
  • 1
  • 8

1 Answers1

0

Implicitly, the type for the variable promise in your example will be ng.IPromise<void> because that's what $q.when() returns.
A variable of type ng.IPromise<void> cannot get an ng.IPromise<EntityBase> object assigned to it.
Depending on what you want to achieve, there are different things you could do.

You can use another variable to hold your later promise:

let anotherPromise = promise.then(() => { ...

You can explicitly declare the type of your variable to be ng.IPromise<any> at the beginning:

let promise: ng.IPromise<any> = self.$q.when();
let promise = promise.then(() => { ...

Or you could have your promise chain ending up actually returning a promise of void:

promise = promise.then(() => {... your chain ...}).then(() => { });

There might be other options as well, but I hope that helps.

Fredy Treboux
  • 3,167
  • 2
  • 26
  • 32