19
loading...
This website collects cookies to deliver better user experience
catch
function on the promise to handle it.catch
method at the end.
const fetchUser => firstName =>
someHttpCall()
.then( response => response.json() )
.then( json => {
const customers = json?.data?.customers ?? []
return customers.filter( c => c.firstName === 'Jesse' )
})
.then( fetchUserDetails )
.catch( error => console.log("http failed:", error) )
async function fetchUser(firstName) {
const response = await someHttpCall()
const json = await response.json()
const customers = json?.data?.customers ?? []
const user = customers.filter( c => c.firstName === 'Jesse' )
const details = await fetchUserDetails(user)
return details
}
async function fetchUser(firstName) {
try {
const response = await someHttpCall()
const json = await response.json()
const customers = json?.data?.customers ?? []
const user = customers.filter( c => c.firstName === 'Jesse' )
const details = await fetchUserDetails(user)
return details
} catch(error) {
console.log("error:", error)
}
}
someHttpCall
and it’s data handling from fetchUserDetails
.async function fetchUser(firstName) {
try {
const response = await someHttpCall()
const json = await response.json()
const customers = json?.data?.customers ?? []
const user = customers.filter( c => c.firstName === 'Jesse' )
try {
const details = await fetchUserDetails(user)
return details
} catch(fetchUserDetailsError) {
console.log("fetching user details failed, user:", user, "error:", fetchUserDetailsError)
}
} catch(error) {
console.log("error:", error)
}
}
const someHttpCall = () =>
Promise.resolve(httpCall())
.then( data => ([ undefined, data ]) )
.catch( error => Promise.resolve([ error?.message, undefined ]) )
function someHttpCall() {
try {
const data = await httpCall()
return [ undefined, data ]
} catch(error) {
return [ error?.message ]
}
}
async function fetchUser(firstName) {
let err, response, json, details
[err, response] = await someHttpCall()
if(err) {
return [err]
}
[err, json] = await response.json()
if(err) {
return [err]
}
const customers = json?.data?.customers ?? []
const user = customers.filter( c => c.firstName === 'Jesse' );
[err, details] = await fetchUserDetails(user[0]);
if(err) {
return [err]
}
return [undefined, details]
}
jsn
instead of json
or if you forget to wrap a function in this style like response.json
, or just generally miss an exception, this style can only help you so much.if(err)
. You have to manually do that each time you call a function that could fail. This violates DRY pretty obnoxiously.const fetchUser => firstName =>
someHttpCall()
.then( response => response.json() )
.then( json => {
const customers = json?.data?.customers ?? []
return customers.filter( c => c.firstName === 'Jesse' )
})
.then( fetchUserDetails )
.catch( error => console.log("http failed:", error) )