Angular - returning value from inside 'then'

Viewed 2119

I've looked at similar questions on StackOverflow but none of them match my specific problem:

I have a TypeScript function in an Angular 6 service, calling a function in another service like this:

Service1:

myArray: Array<IMyInterface>

...

getArray(): Observable<IMyInterface[]> {

    this.myArray= this.service2.getAnArray(1);
    return Observable.of(this.myArray);
}

Service2

getAnArray(myEntityId): Array<IMyInterface> {
  const myArray2: IMyInterface[] = [];

  this.getConnection().then(connection => {
    connection.invoke('GetEntityById', myEntityId).then((someJson: any) => {
      someJson.forEach( x => myArray2.push(x));       
      return myArray2;
    })
  }); 
}

It gives me the error in Service2 A function whose declared type is neither 'void' nor 'any' must return a value.

I need to return myArray2 after connection.invoke('GetEntityById', myId) has resolved, as the array is only populated after that resolves, which is why I try to do it inside then.

How do I do this?

2 Answers

This may/may not suit your needs, but you could just return the Promise from your service method, eg:

getAnArray(myEntityId) {
  const myArray: IMyInterface[] = [];

  // Note the return here
  return this.getConnection().then(connection => {
    return connection.invoke('GetEntityById', myEntityId).then((someJson: any) => {
      someJson.forEach( x => myArray.push(x));       
      return myArray;
    })
  }); 
}

Your calling code would then look like

getAnArray(someId).then(function(theArray) {. . .});

A bit late for this. But someone may find this helpful. You can use Async/Await for this. The reason is every time 'await' occurs, it will hold the thread until the job is done.

 async getAnArray(myEntityId) {
    await this.getConnection();
    try {
      let result = await connection.invoke('GetEntityById', myEntityId).then((someJson: any) => {
      someJson.forEach(x => myArray.push(x));
      return myArray;
      })
   } catch (err) {
  console.log(err);
}

}

To get results (will return a promise):

this.getAnArray(myEntityId).then((data) => {
  console.log('data' , data);
 
});
Related