very basic question here (I'm a Javascript neophyte) that I oddly can't seem to find answered. I'm having trouble storing and displaying the result of a function that uses a fetch call. The code below spits out "undefined" in the console; any thoughts on what might be the problem?
function getApi() { var obj; fetch("https://jsonplaceholder.typicode.com/posts/1").then((res) => res.json()).then((data) => (obj = data)); return obj; } let x = getApi(); console.log(x);
The fetch
method is asynchronous, so obj
is undefined because your code is going to the next instruction without waiting the fetch. You can simply use async/await
method that is a great way to make asynchronous calls because await
will wait for the result before going to the next instruction.
async function getApi() { const response = await fetch("https://jsonplaceholder.typicode.com/posts/1") const obj = await response.json() return obj; } (async() => { let x = await getApi(); console.log(x); })()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.