3

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
  }
}
Nimble Stalker
  • 307
  • 3
  • 14
  • 1
    Instead of awaiting, store a reference to the promise, then await this reference, after awaiting the reference clear the reference. Now when you call check if reference exists, if it does just return the reference. – Keith Jul 01 '21 at 13:10
  • Maybe you are trying to [debounce](https://stackoverflow.com/a/68227965/633183) your query? – Mulan Jul 02 '21 at 16:00

1 Answers1

1

I understand, thank's @Keith

let request: Promise<ElasticsearchAnswer> | undefined

const getOrFetchCategoriesList = async (): Promise<Category[]> => {
  if (categories.length) return categories

  if (!request) {
    request = fetchCategoryList()
    const elasticsearchAnswer: ElasticsearchAnswer = await request
    categories = await elasticsearchAnswer.hits.hits.map(hit => hit._source)
    return categories
  } else if (request) {
    const elasticsearchAnswer: ElasticsearchAnswer = await request
    categories = await elasticsearchAnswer.hits.hits.map(hit => hit._source)
    return categories
  }

  return categories
}
Nimble Stalker
  • 307
  • 3
  • 14