0

I've searched through multiple questions, but I have failed to find one that matches my case.

The following is the simplified version of my code:

function one() {
  let a;
  // does some fetching; takes about 1s
  a = 1; // value is obtained from above line
  return a;
}

function two() {
  let b;
  // does some fetching; takes about 2s
  b = 2; // value is obtained from above line
  return b;
}

function three() {
  let c;
  // does some fetching; takes about 0.5s
  c = 3; // value is obtained from above line
  return c;
}

var variables = [];

function final() {
  variables.push(one());
  variables.push(two());
  variables.push(three());
}
final();

console.log(variables);

What above code gives is [], while the desired output is [1, 2, 3](the order doesn't matter).

I've recognized that the solution is deeply related to async/await and promises(return new Promise(...)), but the implementation mostly fails, either because the await keyword does nothing, or promise comes out <pending>.

Also, through several experiments I've found that the return keyword also runs asynchronously, which means that one(), two() and three() almost certainly returns undefined.

Is there a way to get the return values in a synchronous manner?

Edit 1: The original code works as follows: (1)three different functions fetches json from different APIs which takes some seconds, (2) each functions returns the parsed data from the json, then (3) let the returned value be pushed onto var variables = []; array. I should have added this text in the first place.

pallet0
  • 1
  • 1
  • Your snippets works fine – dippas Jun 09 '22 at 18:02
  • _"but the implementation always fail"_. Start by posting (a simplified version of) such an implementation, because your example code doesn't reflect the real issue. – robertklep Jun 09 '22 at 18:03
  • The example here will work fine. When you say, the implementation does not work - it is in some other location, I guess, where the place where you are calling this function is an async function. Right? – Nagendra Jun 09 '22 at 18:07
  • @Nagendra The mechanism of the code is that (1)the code fetches a json from a server in a function(which takes some seconds), (2)the function returns the parsed data, then (3) let the returned value pushed to the variables array at the end. I should have elaborated on this. sorry for the misleading question..! – pallet0 Jun 09 '22 at 18:11
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Heretic Monkey Jun 09 '22 at 18:15
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all – Berk Kurkcuoglu Jun 09 '22 at 18:24

0 Answers0