【问题标题】:Check if request already send检查请求是否已经发送
【发布时间】:2021-09-13 13:21:29
【问题描述】:

我创建了 2 个发送请求的函数

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
  }
}

【问题讨论】:

  • 不是等待,而是存储一个对承诺的引用,然后等待这个引用,等待引用之后清除引用。现在,当您调用检查引用是否存在时,如果它确实返回引用。
  • 也许你想debounce你的查询?

标签: javascript typescript promise


【解决方案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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2018-08-30
    • 2019-11-18
    相关资源
    最近更新 更多