Search code examples
javascriptasync-awaitfetch-api

async await resolve promise only if I return single value


I have the followin fetch using async/await:

async function postData(url = "", data = {}) {
    // Default options are marked with *
    const response = await fetch(url, {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "cors", // no-cors, *cors, same-origin
        credentials: "include",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    });
    //return response.json(); // parses JSON response into native JavaScript objects
    return {status:response.status, message:response.json()};
}

If I just use the commented return I correctly get the JSON returned by the API, if I use the second return response.json ends up being a

Promise: {"Pending"}

How can I get back from the function both informations? The API is sending me the data like this:

return res.status(200).json("Message to be displayed");

Solution

  • The json() method also returns a promise, you need to await it:

    return { status: response.status, message: await response.json() };
    

    If I just use the commented return I correctly get the JSON returned by the API

    Presumably consuming code was awaiting it somewhere. The overall async function still itself returns a Promise that would need to be awaited/resolved.