0

I am trying to load an array of memberdata into a javascript variable so that I can operate on it from within several different functions. After giving it the old college try, I am lost.

I understand the need for asynchronous functions so as not to block the main thread but the only way I have been able to populate a global variable is by storing the function result to session.Storage and then calling it from there in other functions. While this works it seems like an extra step.

    async function fetchMember($vid) {

    let options = {
        method: 'POST',
        async:false,
        body: JSON.stringify({vid: $vid}),
        headers: {
            'Content-Type': 'application/json',  // sent request
            'Accept': 'application/json'   // expected data sent back
        },
    }
    let response = await fetch('getMember.php', options);
    let $member = await response.text();
    sessionStorage.setItem("member", $member)
     return ($member); // this is a promise because it is in an async function

} //end of function


fetchMember("999999").then ($dog=> console.log ("Then = " + $dog))// $dog is a promise

console.log ("Member = " + $member);  // undefined
$member = session.Storage ("member")  // work as expected

I can ".then" log the result of the promise to the console but for the life of me I can't figure out how to store it in a global variable.

Dave Davis
  • 574
  • 1
  • 4
  • 14
  • I'm slightly confused. My understanding of `let $member = await response.text();` is that because you used `await`, it will not be a promise. Had you left off the await, it would be a promise. – Taplar Aug 19 '20 at 17:18
  • 1
    fetchMember("999999") is not returning a promise – epascarello Aug 19 '20 at 17:21
  • @epascarello Of course it is, it's an async function? Or did you mean that `$dog` (then `then` callback argument) cannot be a promise? – Bergi Aug 19 '20 at 17:42
  • Do not use "*`async:false`*"! Luckily for you, this doesn't work anyway with the fetch api. – Bergi Aug 19 '20 at 17:43
  • @dave-davis Here is a working example with async: https://jsfiddle.net/86jpamf4/ (just replace with your `options` and URL) – Anton Aug 19 '20 at 18:01

1 Answers1

0

As mentioned by @epascarello you are not returning your promise from the then block. A simple (maybe hacky) solution could be to wrap your program in an async function then await the response from your fetchMember function. I made a simple jsFiddle with this in practice.

It is not perfect but it should help you get where you need to go!

JsFiddle: https://jsfiddle.net/3q98gx2t/

(async () => {

// Get the data out of the fetchMember function
// It is in the scope of the overall self executing function.

let test = await fetchMember();

async function fetchMember($vid) {

  let options = {
    method: 'GET',
  }
  let response = await fetch('https://api.coindesk.com/v1/bpi/currentprice.json', options);
  let $member = await response.text();

  return $member; // this is a promise because it is in an async function

} //end of function

console.log("Member = " + test);  // undefined

})();

The problem with the whole then/catch system is that it will always return a promise so, depending on your project, you will end up in a long ass chain of .then(data => something).then(data => something).

For this example I have used a GET request to the Bitcoin API but the principle remains. Just swap your options back in and it should work.

As you can see I have removed the session storage call.

Dharman
  • 30,962
  • 25
  • 85
  • 135
MakingStuffs
  • 666
  • 1
  • 9
  • 17
  • I truly appreciate all of your responses; however, they all seem to require a trip to the server each time I want to get a member's record. I am assuming then, that to have an object persist (be available outside the function that called the server) I must place it either in session or local storage. Please correct me if I am mistaken. – Dave Davis Aug 21 '20 at 15:13
  • @DaveDavis From my understanding the data which was fetched from the server will be available to any function in the scope of the self executing function, without needing to make another fetch call. Variables are stored in the browser process's memory.If you go to the networks tab in your browser and run the code in the following example: https://jsfiddle.net/r3g4znac/ -- You will see the api is only called once. – MakingStuffs Aug 22 '20 at 19:55