Azamat Uzbekov
Azamat Uzbekov

Reputation: 150

How to return a variable from function that gets variable from another function in JavaScript?

I have multiple functions that pass data from one to another. I moved one of the functions to the backend and receive data as API with Axios. Now I cannot manage to assign data from Axios to some local variable. Simple code would be like:

function function1()
 {
   axios({get, url})
  .then(response => {
   globalVariable = response.data;
   function2(globalVariable);
 }

function function2(globalVariable)
  {
   const local = globalVariable;
   return local;
  }

And then inside of function3, I want to do:

function function3() 
 { 
  const from_local = function2()
  from_local
 }

When I try this I receive undefined result. Please help.

Upvotes: 0

Views: 307

Answers (2)

danh
danh

Reputation: 62676

This is what promises are for. No need for globals or jumping through hoops to get the data out. Just remember to await any function that's async, (like axios) and annotate any function that contains an "await" as being async.

// note "async" because it contains await
async function backend() {
  // note await because axios is async
  const response = await axios({get, url});
  return response.data;
}

// same thing up the calling chain
async function middleend() {
  const local = await backend();
  return local;
}

async function frontend() {
  const local = await middleend();
  console.log('ta da! here\'s the data', local);
}

Upvotes: 1

brk
brk

Reputation: 50346

It looks like you are looking for some sort of piping asynchronous operation. By piping I mean result of one function execution will be feed to another.

So basically function1 which is mimicking a axios operation here.

// making an api call
function function1() {
  return fetch('https://jsonplaceholder.typicode.com/todos/1').then((d) =>
    d.json()
  );
}
// some random function
function function2(data) {
  console.log(' Calling function 2 ');
  return data?.title;
}
// some random function
function function3(data) {
  console.log(' Calling function 3 ');
  return `Hello ${data}`;
}
/** a function to resolve functions sequentially. The result of first 
   function will be input to another function. 
   Here ...fns is creating an array like object 
   so array operations can be performed here **/

const runAsynFunctions = (...fns) => {
  return (args) => {
    return fns.reduce((acc, curr) => {
      return acc.then(curr);
    }, Promise.resolve(args)); 
  };
};
// calling runAsynFunctions with and passing list of 
// functions which need to resolved sequentially 

const doOperation = runAsynFunctions(function2, function3);

// resolving the api call first and the passing the result to 
// other functions

function1().then(async(response) => {
  const res = await doOperation(response);
  console.log(res);
});

Upvotes: 0

Related Questions