第一次请求失败后如何处理不同的请求

时间:2019-04-15 19:02:56

标签: javascript api asynchronous xmlhttprequest

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

到目前为止,我只能从以下位置进行抓取:

  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)返回空对象或任何类型的错误时 我该如何处理这种情况?

1 个答案:

答案 0 :(得分:1)

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

在定义后尝试pageOne

但是我为您的情况在stackblitz上进行了拨弄:https://stackblitz.com/edit/js-eufm8h

如果您不了解某些内容,请随时提问。