Reputation: 121
I'm trying to get the first object in a json file that I fetch but It always returns me with pending 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
}
Upvotes: 0
Views: 60
Reputation: 7770
You are returning patchVer before fetch gets completed. You can remove the await and Put return in front of fetch call. Also, wherever you are using this method, either get the output by doing then or await.
Upvotes: 2
Reputation: 2552
Since you have an async function, you should try making everything await-based.
This code should work:
async function getPatchVer() {
const res = await fetch("https://ddragon.leagueoflegends.com/api/versions.json");
const json = await res.json();
return json[1];
}
I have replaced the Promise chain with await. To get the result elsewhere in your code you can do:
getPatchVer().then(version => ...);
//... or if you're inside of another async function
const version = await getPatchVer();
Upvotes: 1