Skip to content

Instantly share code, notes, and snippets.

@moosetraveller
Last active February 28, 2022 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moosetraveller/0f0690da888844a1f736469a68f135a8 to your computer and use it in GitHub Desktop.
Save moosetraveller/0f0690da888844a1f736469a68f135a8 to your computer and use it in GitHub Desktop.
Using fetch with async/await

Cheat Sheet of Thomas Zuberbuehler :)

Retrieve GET

async function retrieveUser(firstName) {

    const response = await fetch(url + "?" + new URLSearchParams({
        firstName: firstName,
    });
 
    let user = await response.json();
    console.log(`User ${user.id} retrieved`);
    
}

retrieveUser("Thomas");

Verbose

function retrieveUser(firstName) {

    fetch(url + "?" + new URLSearchParams({
        firstName: firstName,
    })
    .then(response => response.json())
    .then(user => {
        console.log(`User ${user.id} retrieved`);
    });
    
}

retrieveUser("Thomas");

Create POST

async function createUser(user) {

    const response = await fetch(url, {
        method: "POST",
        body: JSON.stringify(user),
        headers: {
            "Content-type": "application/json; charset=UTF-8",
        },
    });
    
    if (response.status === 201) {
        console.log("created");
    }

);

const user = { id: 1234, firstName: "Thomas", lastName: "Zuberbuehler" };
createUser(user);

Verbose

function createUser(user) {

    fetch(url, {
        method: "POST",
        body: JSON.stringify(user),
        headers: {
            "Content-type": "application/json; charset=UTF-8",
        },
    })
    .then(response => {
        if (response.status === 201) {
            console.log("created");
        }
    });

}

const user = { id: 1234, firstName: "Thomas", lastName: "Zuberbuehler" };
createUser(user);

Delete DELETE

async function deleteUser(userId) {

    const response = await fetch(`${url}/${userId}`, {
        method: "DELETE",
    });
    
    if (response.status === 200) {
        console.log("deleted / entity returned");
    }
    else if (response.status === 204) {
        console.log("deleted / no content returned")
    }
    else if (response.status === 202) {
        console.log("delete operation queued");
    }
    else if (response.status === 404) {
        console.log("entity not found);
    }
    
}

deleteUser(1234);

Verbose

function deleteUser(userId) {

    fetch(`${url}/${userId}`, {
        method: "DELETE",
    })
    .then(response => {
        if (response.status === 200) {
            console.log("deleted / entity returned");
        }
        else if (response.status === 204) {
            console.log("deleted / no content returned")
        }
        else if (response.status === 202) {
            console.log("delete operation queued");
        }
        else if (response.status === 404) {
            console.log("entity not found);
        }
    });
    
}

deleteUser(1234);

Update/Save PUT

async function updateUser(user) {

    const response = fetch(url, {
        method: "PUT",
        body: JSON.stringify(user),
        headers: {
            "Content-type": "application/json; charset=UTF-8",
        },
    });

    if (response.status === 200) {
        console.log("updated / entity returned");
    }
    else if (response.status === 204) {
        console.log("updated / no content returned");
    }
    else if (response.status === 404) {
        console.log("entity not found);
    }

}

const user = { id: 1234, firstName: "Thomas", lastName: "Zuberbuehler" };
updateUser(user);

Verbose

function updateUser(user) {

    fetch(url, {
        method: "PUT",
        body: JSON.stringify(user),
        headers: {
            "Content-type": "application/json; charset=UTF-8",
        },
    })
    .then(response => {
        if (response.status === 200) {
            console.log("updated / entity returned");
        }
        else if (response.status === 204) {
            console.log("updated / no content returned");
        }
        else if (response.status === 404) {
            console.log("entity not found);
        }
    });

}

const user = { id: 1234, firstName: "Thomas", lastName: "Zuberbuehler" };
updateUser(user);

Reading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment