tengo la siguiente función:
private bindSemanticObject(unom: number) { this.setSemanticService .bindObjectsSemanticByUnom(unom) .then( (addressSemantic) => { try { this.setSemanticService.setAddressSemantic(addressSemantic); this.setSemanticService.verifySemanticObject(); this.setSemanticService.setSemanticFields(); this.setSemanticService.saveSemantic().then(() => { this.setSemanticService .stateChangeBindObject() .toPromise() .then(() => {}); this.toastrService.success('Updated...'); this.editLayerFactory.destroy(false); }); } catch (e) { console.log(e); } }, (e) => { this.toastrService.warning(e); }, ) .catch((e) => console.log(e)); } Como puede notar, este código tiene algunos .catch y un bloque de error . ¿Cómo simplificarlo y hacerlo más legible?
Aquí, en 2022, puede simplificar notablemente ese código usando async / await , así:
private async bindSemanticObject(unom: number) { try { const addressSemantic = await this.setSemanticService .bindObjectsSemanticByUnom(unom); this.setSemanticService.setAddressSemantic(addressSemantic); this.setSemanticService.verifySemanticObject(); this.setSemanticService.setSemanticFields(); await this.setSemanticService.saveSemantic(); try { await this.setSemanticService .stateChangeBindObject() .toPromise(); } catch { // You've said in a comment you don't care about // rejections on the part above } this.toastrService.success('Updated...'); this.editLayerFactory.destroy(false); } catch (e) { this.toastrService.warning(e); } }Algunas notas sobre eso:
this.setSemanticService().stateChangeBindObject.toPromise() , así que lo envolví en un try / catch interno.try / catch externo detectará tanto los errores síncronos lanzados por el código como los rechazos de promesa (debido a await ). Si no puede usar async / await por cualquier motivo, puede usar then serie de controladores:
private bindSemanticObject(unom: number) { return this.setSemanticService .bindObjectsSemanticByUnom(unom) .then(addressSemantic => { this.setSemanticService.setAddressSemantic(addressSemantic); this.setSemanticService.verifySemanticObject(); this.setSemanticService.setSemanticFields(); return this.setSemanticService.saveSemantic(); }) .then(() => { return this.setSemanticService .stateChangeBindObject() .toPromise() .catch(() => { /*...suppress...*/ }); }) .then(() => { this.toastrService.success('Updated...'); this.editLayerFactory.destroy(false); }) .catch(e => { this.toastrService.warning(e); }); } Eso no es exactamente lo mismo, no maneja un error sincrónico desde el inicial this.setSemanticService.bindObjectsSemanticByUnom(unom) . Si necesita manejar eso, cambie el comienzo a:
private bindSemanticObject(unom: number) { return Promise.resolve().then(() => this.setSemanticService .bindObjectsSemanticByUnom(unom) ) .then(addressSemantic => { // ...