我是javascript承诺领域的新手,我需要了解它们如何正常工作...
直到知道我一直在我的代码中这样做:
const handleRefresh = () => {
setIsRefreshing(true);
fetchUserData()
.then(async () => { <--------- Using then because I return a promise in fetchUserData
await fetchUserPosts(); <------- Using await here
setIsRefreshing(false);
}).catch(err => { <--------- This will catch the error I have thrown in the function fetchUserPosts or inside the then body
// TODO - Show error
setIsRefreshing(false);
console.log(err)
);
};
const fetchUserData = async () => { <------ async function
const { firebase } = props;
const userId = firebase.getCurrentUser().uid;
const documentRef = firebase.getDatabase().collection("users").doc(userId);
// Fetch all the user information
return documentRef <--------- Returning the promise here
.get()
.then((doc) => {
if (doc.exists) {
// Get all user data
const data = doc.data();
console.log(data);
setUserData(data);
}
})
.catch((err) => {
throw err; <----------- Throwing error
});
};
我不知道我是否在做反模式...但是基本上我需要知道这是否是一种好方法以及我是否正确地进行了操作。
我是否必须将fetchUserData函数声明为异步函数以返回承诺?
我可以在then / catch主体中使用异步等待吗?
我可以这样做吗?
const handleRefresh = async () => {
setIsRefreshing(true);
await fetchUserData()
.then(async () => { <--------- Using then because I return a promise in fetchUserData
await fetchUserPosts(); <------- Using await here
}).catch(err => { <--------- This will catch the error I have thrown in the function fetchUserPosts or inside the then body
// TODO - Show error
console.log(err)
);
setIsRefreshing(false);
};
如果有人指导我,我将不胜感激。谢谢。
答案 0 :(得分:2)
async
和await
这两个词仅是then
和catch
的语法糖。
此:
fetchUserData()
.then(data => return data )
.catch(error => return error)
等效于:
async function getUserData() {
const userData = await fetchUserData()
return userData
}
在这里您要返回任何内容(成功或错误)。如果您想在此处处理错误,只需输入try / catch子句即可。
async function getUserData() {
try {
return await fetchUserData()
} catch (e) {
return e.message
}
}
请注意,您只能在await
函数中使用async
子句。
答案 1 :(得分:1)
1。
只要您不在函数内部等待,函数就可以返回Promise
而不声明为async
,
2。
您不应该在async-await
中使用then
,只需返回一个Promise,它将在以下then
中解决,
3。
使用async-await
语法时,将以声明式方式等待Promises,如下所示:
const handleRefresh = async () => {
try
{
const a = await getA()
// pass the result to another Promise
const b = await getB(a)
const c = await getC(b)
} catch (error)
{
handleError(error)
}
};