Necesito llamar a 3 solicitudes en secuencia, todas ellas con 3 resoluciones
El camino feliz se vería así:
const firstCallResponse = await this.service1.call1(); if (firstCallResponse) { const secondCallResponse = await this.service2.call2(); if (secondCallResponse) { const thirdCallResponse = await this.service3.call3(); if (thirdCallResponse) { console.log('sequence finished successfully); } } }Y no se ve tan mal, pero si trato de agregar esos dos respaldos para cada solicitud, el código se volverá muy complicado.
try { const firstCallResponse = await this.service1.call1(); if (firstCallResponse) { try { const secondCallResponse = await this.service2.call2(); if (secondCallResponse) { try { const thirdCallResponse = await this.service3.call3(); if (thirdCallResponse) { console.log('sequence finished successfully'); } else { console.log('do something, as third call response is not ok'); } } catch { console.log('do something as third call failed'); } } else { console.log('do something, as second call response is not ok'); } } catch { console.log('do something as second call failed'); } } else { console.log('do something, as first call response is not ok'); } } catch { console.log('do something as first call failed'); }¿Hay alguna manera de hacer que este código sea más legible o elegante? El código anterior funcionaría, pero no se ve bien y es extremadamente difícil de leer. ¡Gracias por adelantado!
En primer lugar, puede envolver más de una promesa con try / catch si desea hacer lo mismo cuando fallan. También acepte el argumento en los bloques de captura, ya que pueden decirle dónde se originó el error / más información al respecto, también conocido como
try { // await promise } catch (errorName) { // handle error } Aparte de eso, lo principal que recomendaría es invertir su lógica al verificar los resultados, qué hacer a continuación y agregar declaraciones de return .
try { const firstCallResponse = await this.service1.call1(); if (!firstCallResponse) { console.log('do something as first call failed'); return; } const secondCallResponse = await this.service2.call2(); if (!secondCallResponse) { console.log('do something as second call failed'); return; } // ... // if no errors do something with all results } catch { console.log('do something as first call failed'); }Otro consejo que me gustaría agregar para el final es que si su segunda llamada no requiere nada de los resultados de la primera llamada, puede agruparlos todos en una promesa con
await Promise.all([ this.service1.call1(), this.service2.call2() ])