0

I want to fetch data from API and then display a message "completed" by appending the tag "P" on document. It works fine. However When i want to display message "completed" by appending the tag "P" on document after consuming a Promise, the message is not displaying. On debugging, I found the error as document.body is null. My doubt is fetch also returns a promise (response) and the function in the second example also return a promise Then why both are behaving differently

My first Code

    <!DOCTYPE html>
    <script>
    "use strict";
    function showPara() {
        return new Promise(function(resolve, reject) {
        let img = document.createElement('P');
        img.innerHTML = "example";
        document.body.append(img);
        });
    }
    fetch(`SOMEurl`)
    .then(showPara)
        
    </script>

This displays "example" in the screen ** My Second Code**

    <!DOCTYPE html>
    <script>
    "use strict";
    function showPara() {
        return new Promise(function(resolve, reject) {
        let img = document.createElement('P');
        img.innerHTML = "example";
        document.body.append(img);
        });
    }

    function myProm() {
    return new Promise(function(res, rej){
            res(11);
        });
    }
    myProm
    .then(showPara)
        
    </script>

This does not show anything and on debugging I find document.body is null error

0 Answers0