0

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
      })
      
}
re_search
  • 3
  • 3
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – hindmost Jul 14 '20 at 08:16

2 Answers2

0

You should return the promise like this

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

And then await for the response, in an async function

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

0

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.

Dusan Malusev
  • 163
  • 1
  • 8
  • thank you. i tried both of your samples but the console goes empty (before their was 2 logs - one good and second endefined. now all empty) – re_search Jul 14 '20 at 08:40
  • Sorry, i made mistake, i was just trying to explain to you promises, not to solve the problem, will edit my post and show you the answer. – Dusan Malusev Jul 14 '20 at 08:43
  • Go and checkout links that i provided, you will learn a lot from them and understand javascript, all quirks that you need when you develop application – Dusan Malusev Jul 14 '20 at 08:51
  • yaiiiiiiiii - this is the answer. thank you so much – re_search Jul 14 '20 at 08:53
  • bro if you are still here can you tell me how to get the value outside the scope cause now when i call `let y = asynFunction() console.log(y) ` i get in console Promise object – re_search Jul 14 '20 at 10:29
  • you cannot do that inside javascript. thats not how javascript works. If you have promise you have to use .then or await Check the links i posted, you will learn a lot from them – Dusan Malusev Jul 14 '20 at 11:33
  • you can get the value in a few ways 1. Self calling function ```js (async () => { const y = await asynFunction(); console.log(y); })() ``` 2. Inside another async function ```js async function f() { const y = await asynFunction(); console.log(y); } ``` 3. Using .then ```js function f() { asynFunction().then(y => { console.log(y); }) } ``` – Dusan Malusev Jul 14 '20 at 11:35
  • Please go and learn promises and callbacks and event loop before you start using promises, they are now fundamentals of javascript. ```js fetch(...)``` is promise based, old school XmlHttpRequest is callback based, so you need to understand how they work – Dusan Malusev Jul 14 '20 at 11:39