I created 2 functions that send a request to back
export const getPopularCategoryList = async (): Promise<Category[]> => {
const categories = await getOrFetchCategoriesList()
// my staff
return categories
}
and
export const topCategoriesList = async () => {
let categories = await getOrFetchCategoriesList()
// staff
return categories
}
The question is that if you call the functions sequentially, they will work correctly. Like
getPopularCategoryList()
setTimeout(() => { topCategoriesList() }, 5000)
But I want to make it so that:
If we call function (getOrFetchCategoriesList) and the request has not yet been sent, then we send this request;
If we call function and we have already received a response, then we simply return the received response;
But if we call the function and the request has already been sent, but the response has not yet been received, then we should not send a new request, we should wait for the response to the request and return the result.
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
}
}