【发布时间】:2019-04-16 03:37:46
【问题描述】:
我尝试获取一些对象,但问题是我需要先检查缓存端点上是否有任何对象,如果没有,我应该从常规端点进行正常获取。
到目前为止,我只设法从以下位置获取:
- 普通端点并将所有内容设置为状态,
- 缓存端点并将所有内容设置为状态
任何混合这两种方法的尝试都以失败告终:(
如何混合使用这两种方法?
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