javascript - How do I wrap a return type with a promise in TypeScript? -


i'm writing angular 1.x typescript, , have service (dataservice) that's responsible loading data. simple example, queries node , returns node. in interface:

getnode(id: number): ng.ipromise<node>; 

and implementation:

  getnode(id: number) {             return this.ajaxservice.getnode(id)                 .then((result: ng.ihttppromisecallbackarg<node>) => {                     return new node(result.data.id, result.data.name);                 });         } 

however, introduce service stores these results , returns them if i've queried them before. like:

getnode(id: number) {         var loadednode = this.storageservice.nodes.filter(e => (e.id == id));         if (loadednode.length > 0) {             return loadednode[0];         }          return this.ajaxservice.getnode(id)             .then((result: ng.ihttppromisecallbackarg<node>) => {                 var n = new node(result.data.id, result.data.name);                 this.storageservice.nodes.push(n);                 return n;             });     } 

however, return type fails because it's expecting 'ng.ipromise' rather 'node'. how can wrap 'return loadednode[0];' sort of promise return type rather returning actual object?

you can this, using $q-service:

getnode(id: number) {     var deferred = this.$q.defer();      var loadednode = this.storageservice.nodes.filter(e => (e.id == id));     if (loadednode.length > 0) {         // resolve cached node         deferred.resolve(loadednode[0]);     } else {         // else load through service         this.ajaxservice.getnode(id)             .then((result: ng.ihttppromisecallbackarg<node>) => {                 var n = new node(result.data.id, result.data.name);                 this.storageservice.nodes.push(n);                  // resolve loaded node                 deferred.resolve(n);             });     }      // return promise register callbacks     return deferred.promise; } 

usage:

myservice.getnode(id).then((node) => {     // success }, () => {     // error }); 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -