Search code examples
javascriptgoogle-chrome-extensionfetches6-promise

How to read an object outside a PROMISE .then function


I'm trying to reach an object outside a PROMISE .then() method but when i'm calling the function outside the scope my object become undefined.

my app is a chrome extension.

the function -

function get_API (){
  let url = 'http://example.com'
  fetch(url)
      .then(response => response.json())
      .then (data => { 
        console.log(data)
        return data
      })
    }

Output is good and printing the json from the API url to the console.

but when trying to reach it outside the .then() scope with:

let x = get_API()
console.log(x)

the output is undefined


EDIT: the answer provide bt Dusan Malusev is that i needed to add return before the fetch. now it is working.

working code:

function get_API (){
  return fetch('www.example.com')
      .then(response => response.json())
      .then (data => { 
        console.log(data)
        return data
      })
      
}

Solution

  • To understand promises and callbacks you should checkout this talk Event Loop. Javascript event loop at first runs all synchronous code, that means console.log runs before any of your promise code, that is why x is undefined, callback inside .then(...) will run after all synchronous code and after all callbacks (there is difference between callbacks and promises) You can think of promise like you have postponed something to run later.

    async => await is just a syntactic sugar for promises, it makes our javascript look like synchronous code but it's asynchronous. Everything that i said for promises is still valid inside async => await (they are just promises)

    async function asynFunction() {
       const x = await get_API();
       console.log(x);
    }
    

    this function is the same as:

    function f() {
       get_API().then(data => {
            let x = data; 
            console.log(x));
       })
    }
    

    not as:

    function f() {
       let x;
       get_API().then(data => x = data)
       console.log(x)
    }
    

    Resources for callbacks and promises:

    Async JS Crash Course - Callbacks, Promises, Async Await

    MDN Prmises

    MDN Callbacks

    JavaScript is not the same as other languages, you need to wrap your head around the event loop. and do everything "JavaScript Way".

    Answer to your question:

       function get_API() {
           let url = "http://example.com";
           return fetch(url)
              .then((response) => response.json())
              .then((data) => {
                  console.log(data);
                  return data;
              });
       }
    

    fetch function has two promises by default, first to get the response from the server, second you use to format the data. If you would like to use it like this

    function f() {
       get_API().then(data => {
            let x = data; 
            console.log(x));
       })
    }
    

    your api function has to be changed

      function get_API() {
           let url = "http://example.com";
           return fetch(url)
              .then((response) => response.json());
       }
    

    now your function returns a promise and you can use .then inside another function and get the data.