Doubt about waiting for a Javascript function to return

Asked

Viewed 39 times

0

I’m having a hard time in a situation.

I am using React Native and, in a separate file, I have some global variables and I thought I would also use some functions like this:

//Função "Global" que utilizo para retorna uma única string
global.gServidor = () => {
 //Função que acessa o "Local Storage", estou passando @Config para trazer as Configurações salvas
 getStorage('@Config')
 .then((response) => JSON.parse(response))
 .then((json) => {
   console.log(json);
   return json != null ? json.servidor : "";
 });
};

The problem here is how the result comes, if I call gServidor() anywhere, and spend a console.log in it, undefined is printed. However, the console.log from within it returns the json normally, the problem is in accessing from the outside.

It became a headache because, with fetch() i pass the same difficulty. I thought of setting up a fixed function for simple queries as for example getAPI(), where I would only pass the URL path of the request as a parameter and it would return me a JSON, i.e., getAPI('produtos') and within it would have the entire requisition process of fetch already configured. But I went through the same situation, returns me an undefined value, but if I access from inside, it works.

I’m having a really hard time with this and stuff like async/await.

But one thing at a time, someone can explain to me using my example of gServidor why he returns undefined function outside, and returns right from the inside of it?

1 answer

2


What happens is that its function gServidor is not returning anything. Therefore, if you call, nothing will be returned, although the code is actually running within hers.

You need to use the return, in order to explicitly return the promise in question. Thus:

global.gServidor = () => {
  return getStorage('@Config')
    .then((response) => JSON.parse(response))
    .then((json) => {
      return json != null ? json.servidor : '';
    });
};

Note that now, gServidor is, in fact, returning the value worked. In this case, probably it is a Promise (or Promise-like), since it implements the method then.

So when you call gServidor, shall use the then to wait for the value returned. Another option is to use the await, within an asynchronous function to make that wait.

An example of a call:

gServidor()
  .then((dados) => {
    console.log('Valor retornado:', dados);
  })
  .catch((error) => {
    console.error('Aconteceu um erro:', error);
  });

To learn more, read:

  • 1

    Thank you very much friend, from heart, helped me too, I could understand the concept and with that, several things made sense and now I can give progress in the studies and projects here, helped a lot. Thanks!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.