I want to return some data from a function that uses setTimeout and then use the data somewhere else in the program.
I am just getting started with asynchronous JavaScript and stumbled upon a problem early on. I have a simple function that mimics an API call (or something similar) and uses the setTimeout
function to return the response after some delay. The function looks like this:
// This function mimics the data fetching process
function getData()
{
setTimeout(() => {
return "data";
}, 2000);
}
Now, I know that the setTimeout
function doesn’t belong to the JavaScript runtime and is actually provided by the webAPIs
. So, when I do something like const data = getData();
, the data
variable is initially undefined
as the setTimeout
function is doing its job in another stack, and that the value is returned only after the main stack becomes empty. So, console.log(data);
will log undefined
to the console because the value IS in fact undefined
at the time of calling. The thing I am not being able to understand is that why did the value of data
become undefined
even after 2 seconds? I console log it from the console after running the script and still the value of data
is undefined.
It somewhat makes sense that as we HAD NO assignment in the main stack when the setTimeout
returned the data
after 2 seconds. But, what IS returned by the function to the main stack after the 2 seconds delay? Is there no way to use the returned value by my program? And if there is not, how can I work with the async stuffs in JavaScript?
I know that the fetch
function to get response from APIs return promises and then I can do then
on the response to work with it. But in case of the setTimeout
function or something else that doesn’t return a promise, how can I use the return values from such functions?
In case of promises, the value of the variable is pending
until the data is not fetch
ed and then, it holds either the resolve
or the reject
value, but that is limited to functions that return a promise. Is there no way to use other async functions that do not return a promise?
A way to make our function work is to return a promise, and then we could use the then
on the data returned to do something with the data, but is that the only way to work with asynchronous JavaScript? Are promises inherent to asynchronous JavaScript? Or are there other ways we could achieve this objective?
mukesharyal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
7