如何处理具有多个等待函数的异步函数中的错误



我下面的代码中有一个例子,我想减少代码,这样它就不会像现在这样糟糕。我是异步等待的新手,我不想使用try-and-catch。还有其他方法,但我不能做语法

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);
});
};

您可以使用promise来处理它。参见以下代码:

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');
};

handle函数将promise作为参数,并始终解析它,返回一个带有[data|undefined, Error|undefined]的数组。

如果传递给handle函数的promise解析,则返回[data, undefined];如果它被拒绝,句柄函数仍然解析它并返回[undefined, Error]

最新更新