我创建了两个函数,用于向后端发送请求。
export const getPopularCategoryList = async (): Promise<Category[]> => {
const categories = await getOrFetchCategoriesList()
// my staff
return categories
}
并且
export const topCategoriesList = async () => {
let categories = await getOrFetchCategoriesList()
// staff
return categories
}
问题在于,如果您按顺序调用这些函数,它们将正常工作。 例如:
getPopularCategoryList()
setTimeout(() => { topCategoriesList() }, 5000)
我希望达到以下效果:
如果我们调用函数(getOrFetchCategoriesList)并且尚未发送请求,那么我们就发送这个请求;
如果我们调用函数并且已经收到响应,则只需返回接收到的响应;
但是,如果我们调用函数,请求已经被发送,但尚未收到响应,则我们不应该发送新的请求,而是应该等待请求的响应并返回结果。
const getOrFetchCategoriesList = async (): Promise<Category[]> => {
let response: ElasticsearchAnswer
if (categories.length) return categories
if (!categories.length) {
categoriesLoading = true
response = await fetchCategoryList()
categories = response.hits.hits.map(hit => hit._source)
categoriesLoading = false
return categories
} else if (categoriesLoading) {
// I don't understand what should be here
categories = await response.hits.hits.map(hit => hit._source)
return categories
}
}