-1

i have a result variable where i am trying to populate/assign array using Fetch. It keeps being undefined, also the function keeps returning promises. I can console it but the result is always undefined.

const url = 'https://www.w3schools.com/angular/customers.php';
let result;

function getData(){
    return fetch(url)
              .then(response => response.json())
              .then(data => result = data.records)

}

getData();
let list = getData();

console.log(result)   // undefined
console.log(list)     //  Promise {}

https://stackblitz.com/edit/js-e7x6xj

hangMan
  • 91
  • 1
  • 8
  • does this mean the results will be populated with array once the fetch has finished querying the server and got the result or it it never going to happen since the code is not waiting ?? – hangMan Apr 30 '20 at 18:41
  • 1
    Yes, it will be populated once the fetch has finished. That's *why* fetch uses promises. Your function returns a promise, and clearly you know how to deal with a promise because *so does fetch* - use `.then`. – jonrsharpe Apr 30 '20 at 18:43
  • i did a setTimeout and the result variable is being populated with the array. But the function still returns promise. What is that about?? Also this is in context to populating a UI component in angular, I have it set on the same component, so the UI never gets populated. Is there a way to do it without nesting in multiple components. – hangMan Apr 30 '20 at 18:51
  • Why *wouldn't* it return a promise? That's what it's *supposed* to do. I would strongly recommend reading the linked question carefully, because if you don't understand async you're not getting anywhere fast in web dev. – jonrsharpe Apr 30 '20 at 18:52
  • ok, i think i have to learn more about promises. Thanks – hangMan Apr 30 '20 at 19:20

1 Answers1

1

You can get data in callback functions or once promise is resolved

  function getData(){
return fetch(url)
          .then(response => response.json())
          .then(data => {
           result = data.records
           console.log(result)
        })
     }

If you want to write in a sync fashion (the way you are trying in your code), you should use async function and await for promise, refer this doc: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

Manoj
  • 2,059
  • 3
  • 12
  • 24