[英]Can't assign API data from fetch to variable in function
I have a JS module that is a function that fetches Issue data from our company Github, that I then want assigned to a variable:我有一个 JS 模块,它是 function,它从我们公司 Github 获取问题数据,然后我想将其分配给一个变量:
import { request } from "https://cdn.skypack.dev/@octokit/request";
let issueData
async function getIssues() {
const issueAPI = await request("GET repos/{owner}/{repo}/issues", {
baseUrl: "https://company.com/api/v3/",
owner: "me",
repo: "exampleRepo",
});
window.issueData = issueAPI.data
return issueAPI.data
}
export { getIssues, issueData }
I can't seem to get the issueAPI.data
to assign to my variable issueData
?我似乎无法将
issueAPI.data
分配给我的变量issueData
? What's going wrong here?这里出了什么问题? I have a feeling it's something to do with the promises/async or scope but just can't work it out.
我觉得这与 promises/async 或 scope 有关,但无法解决。
You are assigning issueAPI.data
to a window variable called issueData
, which is not the same variable that you have defined with let
on your snippet.您将
issueAPI.data
分配给名为issueData
的 window 变量,该变量与您在代码片段中使用let
定义的变量不同。 If you want to assign to your declared variable, you just need to do this.如果你想分配给你声明的变量,你只需要这样做。
let issueData = await getIssues()
If there are no other errors in the function, this should correctly assign what you want to your declared variable.如果 function 中没有其他错误,这应该正确地将您想要的内容分配给声明的变量。
Also you can drop the window.issueData = issueAPI.data
unless you really want to have that accesible from the window object.你也可以放弃
window.issueData = issueAPI.data
除非你真的想从 window object 中获得它。
EDIT: As Jeremy points out, this would require top-level await.编辑:正如杰里米指出的那样,这需要顶级等待。 A workaround also provided by Jeremy:
Jeremy 还提供了一种解决方法:
let issueData
( async () => { issueData = await getIssues() })()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.