简体   繁体   English

Returning an JSON object from an API call using a function in Javascript

[英]Returning an JSON object from an API call using a function in Javascript

very basic question here (I'm a Javascript neophyte) that I oddly can't seem to find answered.这里非常基本的问题(我是 Javascript 新手),奇怪的是我似乎无法找到答案。 I'm having trouble storing and displaying the result of a function that uses a fetch call.我无法存储和显示使用 fetch 调用的 function 的结果。 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. fetch方法是异步的,因此obj是未定义的,因为您的代码将进入下一条指令而无需等待 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/await方法,这是一种进行异步调用的好方法,因为await会在执行下一条指令之前等待结果。

 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); })()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM