August Williams
August Williams

Reputation: 929

Why is my fetch response showing a promise even after reading the response stream?

I'm calling an API, which is returning a body that I need to access. Calling the API via Postman works as expected. The JavaScript code is below:

async function checkIfCheater(nameToCheck) {
    let testJson = {
        "GameName" : nameToCheck
    }

    await fetch(apiGatewayCheckCheaterLocal, {
        method: 'POST',
        mode: 'cors',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(testJson)
    }).then(response=>response.json()).then(data=>{ return data; });
}

I have tried accessing the response in multiple ways. The example here follows the accepted answer here. However, despite this, the returned value is still a Promise {<pending>} object that I cannot access the body of.

How come my object is still a promise, despite following the answer on that link, and how can I fix it?

Upvotes: 0

Views: 431

Answers (1)

0xdw
0xdw

Reputation: 3842

It should be corrected as follow,

async function checkIfCheater(nameToCheck) {
    let testJson = {
        "GameName": nameToCheck
    };

    const res = await fetch(apiGatewayCheckCheaterLocal, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(testJson)
    });

    const data = await res.json();

    return data;
}

checkIfCheater('name').then(data => console.log(data));

Upvotes: 2

Related Questions