0

I'm trying to store the response from a fetch API call in a global variable. However, the variable which I store the result in returns undefined.

I've tried to use async/await to resolve this issue, but it doesn't seem to have help the situation. I appear to get to a state where a pending promise is returned, but that isn't the desired result.

var obj;

async function getEmails() {
    
    let url = "https://api2.frontapp.com/inboxes/xxxxxx/conversations?limit=50";

    return fetch(url, {
    body: undefined,
    method: 'GET',
    headers: {
        'Host': 'api2.frontapp.com',
        'Authorization': 'Bearer xxxxxx',
        "Accept": "application/json",
    }
    })
    .then(res => res.json())
    .then(response => {
        obj = response;
    })
}

getEmails();
console.log(obj);

I expected obj to return the JSON data of the fetch, but it instead returns undefined.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
danny03
  • 17
  • 4

1 Answers1

0

The problem is that you are trying to read the response before the request is finished. Try this:

getEmails().then(() => {
  console.log(obj);
});

or alternatively, using the await keyword:

(async () => {
  var obj;

  async function getEmails() {

      let url = "https://api2.frontapp.com/inboxes/xxxxxx/conversations?limit=50";

      return fetch(url, {
      body: undefined,
      method: 'GET',
      headers: {
          'Host': 'api2.frontapp.com',
          'Authorization': 'Bearer xxxxxx',
          "Accept": "application/json",
      }
      })
      .then(res => res.json())
      .then(response => {
          obj = response;
      })
  }

  await getEmails();
  console.log(obj);
})();
Matteo Basso
  • 2,694
  • 2
  • 14
  • 21
  • But I want to be able to store the json returned from getEmails in the variable obj. – danny03 May 23 '19 at 20:43
  • `getEmails` stores the json into the `obj` variable but you cannot be sure when it will happen since it is an async action. If you want you can use the `await` keyword... I'll update my answer – Matteo Basso May 23 '19 at 20:45
  • My problem with this solution is that the function will run immediately as it is self-invoked, which isn't what I want. Would there be no other way to store the data globally? – danny03 May 23 '19 at 20:52
  • @danny03 What you are doing currently DOES store it globally. but you cannot *access* the data until the data exists. – Kevin B May 23 '19 at 20:54
  • @KevinB So how could I go around accessing the data once I'm sure that it does exist? – danny03 May 23 '19 at 20:55
  • The same way you do any other object/property/array etc. – Kevin B May 23 '19 at 20:55
  • @KevinB Um? Care to elaborate? – danny03 May 23 '19 at 20:58
  • If `obj` contains an object, you can access that object. `console.log(obj.foo)`. – Kevin B May 23 '19 at 20:58
  • you are actually storing the json into `obj` but you can use it only if you `await getEmails()` or into the `getEmails.then`. Otherwise, you cannot be sure sure that `obj` is initialized. – Matteo Basso May 23 '19 at 21:00