Tengo la primera función que se ve así:
private async checkIsExists(): Promise<Boolean> { this.repositoryService.getEntry(this.id) .subscribe({ error: (err) => { return false; } }); return true;Esta función debería devolver falso si ocurre algún error, como un 404. En el servicio de repositorio tengo la función getEntry que se ve así:
getEntry(entryId: string) { return this.collectionsApi.getEntry(entryId); }Que no es una función asíncrona. Mi pregunta sería, ¿cómo podría hacer que la función de verificación funcione correctamente? En este momento, devuelve verdadero sin importar qué, porque no espera a que se obtengan los datos, me gustaría cambiar solo esta función. si es posible
Actualización: cambié la función y la llamada a esto:
private checkIfShareExists(): Observable<Boolean> { return this.repositoryService.getEntry(this.id).pipe( catchError(() => of(false)), map( () => { return true; }) )} ... this.checkIfShareExists().subscribe(exists => { console.log(exists); });Pero aún imprime verdadero siempre, aunque se arroja el error
Suponiendo que getEntry sea un observable (dado que se está subscribe a él), puede usar async await si lo transforma en una promesa:
private async checkIsExists(): Promise<Boolean> { return await this.repositoryService.getEntry(this.id).toPromise().then(r => true).catch(r => false); }Después de esto, puede usar esa función dentro de otro bloque de espera asíncrona para obtener su resultado booleano:
async myFunc(){ var couldGet = await this.myComponent.checkIsExist(); if(!couldGet) { console.error("sadface.jpg") } }