检查请求是否已发送。

3
我创建了两个函数,用于向后端发送请求。
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
  }
}

1
不要使用 await,而是存储一个 Promise 的引用,然后等待这个引用。在等待完引用后清除它。现在当你调用时,检查引用是否存在,如果存在就返回引用。 - Keith
也许你正在尝试对查询进行去抖动(debounce)? - Mulan
1个回答

1

我明白了,谢谢 @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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接