在react中链接异步/等待调用



我有一个应用程序,可以将《纽约时报》畅销书项目添加到数据库中。目前,用户可以将畅销书添加到数据库中,即使它已经存在于数据库中。我希望能够链接API调用,这样,如果用户试图保存一个项,应用程序首先检查该项是否在数据库中,并且只有在没有继续保存该项时才进行检查。

这是我现有的代码:

const [currentInDb, setCurrentInDb] = useState(false);
interface bookInt {
title: string;
author: string;
}
const handleDbCheck = async(book: bookInt) => { 
setCurrentInDb(false); 
let targetObj = {
title: book.title, 
author: book.author, 
list: selectedCategory
}
try {
let url = baseURL + "/read-all";
axios.get(url).then((res) => {
for (let i = 0; i < res.data.length; i++){
let current = res.data[i]
if (current.title === targetObj.title && current.list === targetObj.list){
setCurrentInDb(true); 
}    
}
});
} catch (error) {
console.log(error);
}
}

const handleSaveBook = async (book: bookInt) => {
if (currentInDb){
console.log('handleSaveBook stopped early because item in db'); 
return;
} 
try {
let newObj = {
title: book.title,
author: book.author,
list: selectedCategory,
};
let postURL = baseURL + "/create";
axios.post(postURL, newObj).then((response) => {
console.log('new item added'); 
});
} catch (error) {
console.log("error: ", error);
}
};

const handleCheckAndSave = async(book: bookInt): Promise<any> => {
await handleDbCheck(book)
.then(res => handleSaveBook(book))
}

奇怪的是,在页面重新加载时,当我第一次尝试将一个项目添加到已经存在的数据库时,我可以添加一个重复项。然后,如果我再次尝试添加,它正确地不允许我添加。想法?

异步函数中不需要使用.then。您可以简单地使用await&连锁你的异步请求。

const [currentInDb, setCurrentInDb] = useState(false);
interface bookInt {
title: string;
author: string;
}
const handleDbCheck = async(book: bookInt) => { 
setCurrentInDb(false); 
let targetObj = {
title: book.title, 
author: book.author, 
list: selectedCategory
}
try {
let url = baseURL + "/read-all";
const res = await axios.get(url)
for (let i = 0; i < res.data.length; i++){
let current = res.data[i]
if (current.title === targetObj.title && current.list === targetObj.list){
setCurrentInDb(true); 
}    
}
} catch (error) {
console.log(error);
}
}

const handleSaveBook = async (book: bookInt) => {
if (currentInDb){
console.log('handleSaveBook stopped early because item in db'); 
return;
} 
try {
let newObj = {
title: book.title,
author: book.author,
list: selectedCategory,
};
let postURL = baseURL + "/create";
const response = await axios.post(postURL, newObj)
console.log(response)
} catch (error) {
console.log("error: ", error);
}
};

const handleCheckAndSave = async(book: bookInt): Promise<any> => {
await handleDbCheck(book)
await handleSaveBook(book)
}

最新更新