0

I'm just now sure why this isn't working. I've also tried an async/await solution, but in all cases, the variable doesn't have the data assigned to it.

let variable = []

let getProducts = () => {
  return fetch(baseUrl + limitUrlModifier + pageUrlModifier + toString(pageNumber) + includeFieldsUrlModifier, getFetchOptions)
    .then(response => response.json())
    .then(data => variable = data.data)
}

getProducts()
jFasaJr
  • 497
  • 4
  • 17
  • It will eventually... when are you trying to access it? Are calling `.then` on the promise returned by getProducts so that you wait for the promise to resolve? – Nicholas Tower May 28 '20 at 10:35
  • @NicholasTower I thought that was the point of the function in the .then, to resolve and then continue? – jFasaJr May 28 '20 at 10:41
  • Well to achieve that you should use `async` and `await`. But again that is async function. Anything accessing it, should again async await or .`then` to resolve. – noitse May 28 '20 at 10:42
  • So if I do something like ```let runScript = () => { async () => { productList = await getProducts() } console.log(productList.length) }``` It shows 0 for length even with 2 items in the array later in the script. – jFasaJr May 28 '20 at 10:50
  • ... cause you never call the async function expression you've built up, also the log should be inside of it ... – Jonas Wilms May 28 '20 at 11:01
  • `I thought that was the point of the function in the .then, to resolve and then continue?` Basically yes, but the code that does the continuing needs to be in the function. If the only thing you're doing in the function is assigning to a variable, it's not very useful. So the code that actually uses `variable` needs to be in the .then callback, at which point, there's little reason to have `variable` at all – Nicholas Tower May 28 '20 at 11:53

0 Answers0