我正在尝试获取json文件中的第一个对象,但它总是返回挂起的promises。
async function getPatchVer() {
let patchVer = null
await fetch("https://ddragon.leagueoflegends.com/api/versions.json")
.then(res => res.json())
.then(json => patchVer = json[1])
return patchVer
}发布于 2020-01-27 06:40:14
在fetch完成之前返回patchVer。您可以删除await并将return放在fetch调用的前面。此外,无论您在哪里使用此方法,都可以通过执行then或await获得输出。
发布于 2020-01-27 06:39:42
既然你有一个异步函数,你应该尝试让所有的东西都是基于等待的。
下面的代码应该可以工作:
async function getPatchVer() {
const res = await fetch("https://ddragon.leagueoflegends.com/api/versions.json");
const json = await res.json();
return json[1];
}我已经用await替换了Promise链。要在代码中的其他位置获得结果,您可以这样做:
getPatchVer().then(version => ...);
//... or if you're inside of another async function
const version = await getPatchVer();https://stackoverflow.com/questions/59923377
复制相似问题