I’m trying to grab values from event handlers and asynchronous functions like AJAX calls and store them in a variable. Here’s my current code:
let result = "";
someInput.onchange = () => {
result = someInput.value;
};
fetch("someapi")
.then(response => response.json())
.then(data => {
result = data.foo;
});
some.api.call(42, (data) => {
result = data.bar;
});
someDiv.textContent = result;
The problem is that nothing shows up in someDiv
. I understand that JavaScript is asynchronous, but I’m not sure how to properly handle the values I get back from these functions.
How can I get the values from event handlers and AJAX calls into my result
variable?
Or, how can I wait for these asynchronous functions to finish before setting the content of someDiv
?
I’ve tried a few different things, but nothing seems to work. Any help would be greatly appreciated!
Iwan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.