Hello everyone! I’m experiencing an problem with fetch(). I want to pass fetch data to api_data global variable, so I able to use in rest of file.
In getData() function, everything works well. But I cannot access the data from outside in any way. At bottom, console.warn(api_data) returns "undefined".
api_data is being assigned the value of data.results inside a callback function that is executed asynchronously. Therefore, when console.warn(api_data) is called, the value of api_data is still undefined because the callback function has not yet been executed.
example using async/await:
Hey @aykut1 , looking good so far. Your code to fetch is asynchronously fetching data in the background so your program is moving onto the next set of instructions before the data is returned. That is the reason why you see undefined. Zaklina is on the right track and you need to use async/await.
The code isn’t any less asynchronous now than it was before. Any synchronous code you put after it will still not wait for the asynchronous code. Without knowing how you are trying to use the data we can’t help with the code structure.
You can run/call the synchronous code/function inside the asynchronous function at the bottom (after the fetch is done) and/or pass the resolved data to the function that needs it.
You can call an asynchronous function that returns the promise or data inside another function that needs the data.
What you can’t do is assign the data to a top-level variable and expect synchronous code to have access to it before the asynchronous code has finished.
Think of it like an event handler. It is not going to block the app and stop all code execution until the event has fired, that would be horrible. And you can’t access the data it produces before it has finished running which will happen at some indeterminate point or possibly never.
btn.addEventListener('click', () => topLevelVar = 'some data'); // non-blocking
console.log(topLevelVar); // undefined/initial value of topLevelVar
Some example code, useData will run twice with this setup which you wouldn’t want. You likely wouldn’t both pass and await the same data. Anyway, it’s just an example.
Code example
let data = 'Initial data';
const getUsers = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
const users = await response.json();
data = users;
useData(users);
return users;
};
getUsers();
function useData(paramData) {
console.log('2. paramData', paramData); // 2. param data from api
console.log('3. top-level data', data); // 3. top-level data from api
}
async function getData() {
const awaitedData = await getUsers();
console.log('4. awaitedData', awaitedData); // 4. awaited data from api
console.log('5. top-level data', data); // 5. top-level data from api
}
getData();
console.log('1.', data); // 1. Initial data