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.