Home > Net >  my async function is returning both fullfiled and pending
my async function is returning both fullfiled and pending

Time:01-29

async function apiFetch() {
  let response = await fetch("https://dog.ceo/api/breeds/image/random");
  let success = await response.json();
  const img = document.createElement("img");
  img.src = success.message;
  div.append(img)
}

then console is telling both fullfiled and pending when called function in console apiFetch()

CodePudding user response:

From your sniff code, I guess you want to get the image URL and display into HTML.

I made two separate functions and on click event function.

First (getImageUrl()) is to get image URL.

Second (loadImage()) is to display image into HTML.

Last (updateImage()) is combine and call sequentially.

This demo will works.

<!DOCTYPE html>
<html>

<head>
    <style>
        img {
            display: block;
            margin-left: auto;
            margin-right: auto;
        }
    </style>
</head>

<body>
    <h2>Dog picture</h2>
    <button onclick="updateImage()">Update Image</button>
    <dev id="container"></dev>

    <script>
        async function getImageUrl() {
            const response = await fetch("https://dog.ceo/api/breeds/image/random");
            const data = await response.json();
            return data.message;
        }
        async function loadImage(url) {
            const options = {
                method: "GET",
            };

            let response = await fetch(url, options);

            if (response.status === 200) {
                const imageBlob = await response.blob();
                const imageObjectURL = URL.createObjectURL(imageBlob);

                const image = document.createElement("img");
                image.src = imageObjectURL;

                const container = document.getElementById("container");
                //   remove existing image
                while (container.firstChild) {
                    container.removeChild(container.firstChild);
                }
                //   update image
                container.append(image);
            } else {
                console.log("HTTP-Error: "   response.status);
            }
        }
        async function updateImage() {
            getImageUrl().then((imageURL) => {
                loadImage(imageURL);
            });
        }
    </script>
</body>

</html>

Result

enter image description here

References

Downloading images with node.js

How to Use Fetch with async/await

How do I clear the content of a div using JavaScript?

The onclick Event

Fetch image from API

  •  Tags:  
  • api
  • Related