Search code examples
javascriptreactjsaxiosarchitectural-patterns

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 :

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. Now I have a particularity about my function is that, I use 2 nested 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.

Anyone an idea ?


Solution

  • 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://...')
        }
    }