Tengo una función asíncrona que se llama al comienzo de mi código, y solo cuando se hace, pueden suceder más cosas. Normalmente sería algo como
const initialCheck = () => { return fetch('https://reqres.in/api/users') .then(r => { // do things return r }) } const actualStuff = () => { console.log('hello') } initialCheck() .then(r => { actualStuff() }) El objetivo de esta verificación inicial es asegurarse de que el punto final HTTP ( https://reqres.in/api/users ) sea realmente accesible. Por lo tanto, debería tener en cuenta un problema de conexión y mi solución fue catch() el posible error:
const initialCheck = () => { return fetch('https://thissitedoesnotexistihopeatleast') .then(r => { // do things when the endpoint is available return r }) .catch(err => { // do something when the endpoint is not availble // nothing is returned }) } const actualStuff = () => { console.log('hello') } initialCheck() .then(r => { actualStuff() })Mi pregunta: ¿por qué funciona el código anterior?
catch() se ejecuta (y el then() en esa función no lo es), no devuelve nada y, a pesar de eso, .then(r => {actualStuff()}) genera lo que se espera ( hello en la consola).
¿Qué recibe then() realmente? (que no return )
Un .catch encadenado a una Promesa resultará en una Promesa que:
.catch , si .catch regresa normalmente.catch mismo arroja un errorAsi que
const chainedPromise = somePromise.catch(() => { // no errors here // nothing returned }) Si .catch definitivamente no arroja, entonces chainedPromise definitivamente se resolverá (y no rechazará), y dado que no se devuelve nada, chainedPromise se resolverá como undefined .
Asi que
initialCheck() .then(r => { actualStuff() }) funciona porque initialCheck devuelve una Promesa que resuelve (a undefined ).
Si devolvió algo del .catch y se ingresó el .catch , lo verá en .then encadenado a él más tarde:
const initialCheck = () => { return fetch('https://doesnotexist') .catch(() => { return 'foo'; }); } const actualStuff = (r) => { console.log(r); console.log('r is foo:', r === 'foo') } initialCheck() .then(r => { actualStuff(r); })