Bora Ciner
Bora Ciner

Reputation: 121

Why does my promises that I fetch ends up with pending results

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

Answers (2)

Ashish Modi
Ashish Modi

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

Mat Sz
Mat Sz

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

Related Questions