【发布时间】:2019-10-10 11:04:03
【问题描述】:
我正在尝试将来自 fetch api 调用的响应存储在 gloval 变量中。但是,我存储结果的变量返回未定义。
我尝试使用 async/await 来解决这个问题,但它似乎对这种情况没有帮助。我似乎达到了返回未决承诺的状态,但这不是预期的结果。
var obj;
async function getEmails() {
let url = "https://api2.frontapp.com/inboxes/xxxxxx/conversations?limit=50";
return fetch(url, {
body: undefined,
method: 'GET',
headers: {
'Host': 'api2.frontapp.com',
'Authorization': 'Bearer xxxxxx',
"Accept": "application/json",
}
})
.then(res => res.json())
.then(response => {
obj = response;
})
}
getEmails();
console.log(obj);
我希望 obj 返回 fetch 的 json 数据,但它却返回 undefined。
【问题讨论】:
-
这是异步调用 .then(response => { obj = response; console.log(obj) })
-
@Code-EZ 我已经有那行了。我想在程序的其他地方使用全局变量,但它仍然未定义。
标签: javascript api promise fetch