2

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 ?

George Koniaris
  • 304
  • 2
  • 9
Tibo
  • 396
  • 3
  • 18
  • Don't have the common function handle the different return calls in the end. – Bergi Apr 08 '20 at 16:52
  • 2
    Your function should *always* return a promise, even if it found the value in cache synchronously - use `return Promise.resolve(data)` – Bergi Apr 08 '20 at 16:54

2 Answers2

1

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://...')
    }
}
Adam Jeliński
  • 1,338
  • 1
  • 4
  • 18
1

Yes, you can do it with nested functions. Convert your main function to async & you are good to 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
    })
  }
}