'How to handle error in an async function with multiple await functions?
I have the example from my code down below I want to reduce the code so it lose the bad state that it has now I am new to async await and i dont want to use try and catch. there is the other way but I cannot do the syntax
const UpdateData = async (selected: any) => {
// Clients
const docRefClients = doc(db, 'Data', _authContext.currentUser.uid);
let arr: any = [];
// Get The doc
await getDoc(docRefClients)
.then((docSnap) => {
arr = docSnap.data()?.clients;
})
.then((res) => {
console.log(res);
})
.catch((error) => {
const errorCode = error.code;
alert(errorCode);
});
const updateData = arr.map((el: any) => {
if (el.clientId === selected.clientId) {
return selected;
}
});
console.log(updateData);
// Modify
await updateDoc(docRefClients, {
clients: arr,
})
.then((res) => {
console.log(res);
})
.catch((error) => {
const errorCode = error.code;
alert(errorCode);
});
};
Solution 1:[1]
You can handle it using promises. See code below:
const handle = (promise) => {
return promise
.then(data => ([data, undefined]))
.catch(error => Promise.resolve([undefined, error]));
}
const UpdateData = async (selected: any) => {
// Clients
const docRefClients = doc(db, 'Data', _authContext.currentUser.uid);
let arr = [];
// Get The doc
let [get, getError] = await handle(getDoc(docRefClients));
arr = docSnap.data()?.clients;
console.log(arr);
// Throws an error and handles it with promises
if(getError) throw new Error('Could not fetch details');
const updateData = arr.map((el) => {
if (el.clientId === selected.clientId) {
return selected;
}
});
console.log(updateData);
// Modify
let [update, updateError] = await handle(updateDoc(docRefClients, {
regions: arrayUnion("greater_virginia")
}));
console.log(update);
// Throws an error and handles it with promises
if(updateError) throw new Error('Could not update details');
};
The handle function takes a promise as an argument and always resolves it, returning an array with [data|undefined, Error|undefined].
If the promise passed to the handle function resolves it returns [data, undefined];
If it was rejected, the handle function still resolves it and returns [undefined, Error].
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marc Anthony B |
