【问题标题】:How can I manage to make diffrent request after first request with failed status在第一次请求失败后,我如何设法提出不同的请求
【发布时间】:2019-04-16 03:37:46
【问题描述】:

我尝试获取一些对象,但问题是我需要先检查缓存端点上是否有任何对象,如果没有,我应该从常规端点进行正常获取。

到目前为止,我只设法从以下位置获取:

  1. 普通端点并将所有内容设置为状态,
  2. 缓存端点并将所有内容设置为状态

任何混合这两种方法的尝试都以失败告终:(

如何混合使用这两种方法?

const getCache = async () => {
  try {
    const apiCall = await fetch(fetchCacheEndpoint)
    const data = await apiCall.json()
    return data
  } catch (e) {
    console.log(e);
  }

}
const pageOne = getCache().then((result) => {
  const convertedOBj = result.doSomeSeriousStuff()
  this.setState({
     desiredObj: convertedOBj 
  })
})

我希望做这样的事情

const getCache = async () => {
  try {
    const apiCall = await fetch(fetchCacheEndpoint)
    const data = await apiCall.json()
    return data
  } catch (e) {
    console.log(e);
  }
}
let convertedOBj 
const pageOne = getCache().then((result) => {
 if ((result === undefined) || (!result) || (result && !result.length > 0)) {
    const makeRegularFetch = async () => {
      const regularFetch = await fetch(regularEndPoint)
      const data = await regularFetch.json()
    }
    const pageTwo = makeRegularFetch ().then((result) => {
      convertedOBj = result.doSomeSeriousStuff()
      this.setState({
        desiredObj: convertedOBj 
      })
    })
 } else {
   convertedOBj = result.doSomeSeriousStuff()
   this.setState({
     desiredObj: convertedOBj 
   })
 }

})

在第一次获取 (getCache) 失败后,有另一个获取 (makeRegularFetch) 到第二个端点,这总是好的,但只有在 first(getCache) 返回空对象或任何类型的错误的情况下 我该如何处理这种行为?

【问题讨论】:

    标签: javascript api asynchronous xmlhttprequest


    【解决方案1】:

    从我在您的代码的第二部分中可以看到,您永远不会执行您的 pageOne 函数。

    在定义后尝试pageOne()

    但是我为你的情况做了一个关于 stackblitz 的小提琴:https://stackblitz.com/edit/js-eufm8h

    如果有不明白的地方,欢迎提问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多