Javascript : 在函数中混合异步和同步(缓存和 Ajax 请求)

Javascript : mix Async with Sync in a function (cache and Ajax request)

我想弄清楚如何从一个看起来像这样的函数中混合 2 个不同的 returns(异步/同步):

getVideo(itemID){
  let data = localStorage.getItem(itemID)

  if ( data ) {
    return data;
  } else{
    axios.get('http://...')
  }
}

如您所见,我正在使用 React 来处理我的请求,而我的 objective 是从缓存中获取数据而不是在线获取数据。现在我对我的函数有一个特殊性,我使用 2 个嵌套的 axios.get('http://...')。

所以我的情况是:

- GET item online
-- GET SubItem online
-- OR get SubItem from cache if exists
---- Get SubSubItem online
---- Or get SubSubItem from cache if exists 
------ Update State 

我希望能够将我的 GET 调用放入一个函数中,但不确定如何做到这一点并同时处理不同的 return 调用。

有人有想法吗?

无法混合使用同步和异步,但您始终可以毫无问题地将同步转换为异步:

getVideo = async (itemID) => {
    let data = localStorage.getItem(itemID)

    if ( data ) {
        return data;
    } else {
        return await axios.get('http://...')
    }
}

是的,您可以使用嵌套函数来完成。将您的主要功能转换为异步功能,一切顺利。请参阅下面的实现:

async function getVideo(itemID){
  let data = localStorage.getItem(itemID)

  if ( data ) {
    return data;
  } else{
    await axios.get('http://...', async r => {// Async callback to use handle another async request
        console.log(`Axios response: ${r}`)
        // do another async stuff here in the same way
    })
  }
}