简体   繁体   English

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

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

I'm trying to figure out how to mix 2 different returns (async / sync) from a function that would look like this:我试图弄清楚如何从看起来像这样的 function 混合 2 个不同的返回(异步/同步):

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

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

As you can see I'm using React to handle my requests and my objective is to go fetch data from cache instead of getting it online.如您所见,我正在使用 React 来处理我的请求,我的目标是 go 从缓存中获取数据而不是使其在线。 Now I have a particularity about my function is that, I use 2 nested axios.get('http://...').现在我对我的 function 有一个特殊性,我使用 2 个嵌套的 axios.get('http://...')。

So my scenario is:所以我的情况是:

- 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 

I'd love to be able to put my GET call into a function, but not sure how to do that AND handling different return calls at the same time.我希望能够将我的 GET 调用放入 function,但不知道如何做到这一点并同时处理不同的返回调用。

Anyone an idea?任何人的想法?

There is no way to mix sync and async, but you can always turn sync into async without an issue:没有办法混合使用同步和异步,但是您始终可以将同步转换为异步而不会出现问题:

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

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

Yes, you can do it with nested functions.是的,您可以使用嵌套函数来做到这一点。 Convert your main function to async & you are good to go.将您的主要 function 转换为异步并且您对 go 很好。 See the implementation below:请参阅下面的实现:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM