Calling to Rest function from attached script returns undefined instead of data

I am doing a Rest API in javascript for improving myself and having a little of fun…
And the API works well!

const getMethod = function(reqType){
    let req;
    if(!reqType){
        req=server+":"+port;
    }
    else{
        req=`${server}:${port}/${reqType}`;
    }
    fetch(req,{mode:'cors'})
    .then(response=>{
        if(response.ok===true){
            response.json().then(res=>{
                console.log(res);
                return res;
            }).catch(err=>console.error(err));
        } else{
            console.error('Error. Status code: '+ response.status + ' '+ response.statusText);
            return {message: 'Failed'};
        }
    })
    .catch(err=>{console.error(err);
        return {message: 'Failed'}
    });
}

I know it can be improved, but for now it works. console.log(res) actually shows an Array of Mock Data from Express server.

The thing is that, in order to avoid creating another server, I attached into the HTML the following code:

<script type="text/javascript">
        window.onload = function(){
            console.log(getMethod());
            const res = getMethod();
            console.log(res);
            classifyInfo(res);
            console.log("Get Information");
        }

        const classifyInfo = function(data){
            const ul=document.getElementsByTagName('section')[1].getElementsByTagName('ul');
            let content='';
            if(data['peliculas']&&data['clasificaciones']){
                const movies=data['peliculas'];
                const classes=data['clasificaciones'];
                for(let i=0;i<classes.length;i++){
                    const clasMovies = searchInfo(movies, classes[i].nombre);
                    content+=`<li>${classes[i].nombre} <ul>`;
                    for(let j=0;j<clasMovies;j++){
                        content+=`<li>${clasMovies[j].nombre}</li>`;
                    }
                    content+='</ul></li>';
                }
            }
        }

        const searchInfo = function(data, term){
            const returnElement = data.filter(el=>el['clasificacion']==term);
            return returnElement;
        }
    </script>

At onload function, res becomes undefined even if afterwards the console shows the array. However, I don’t know why it is doing this.

I have tried to use await for waiting the response, but that does not work either.

Any ideas would be appreciated 😉

1 thought on “Calling to Rest function from attached script returns undefined instead of data”

  1. Well… It was easier than I thought…

    I suppose that I should just surround asynchronous await order with some try/catch just in case…

    I modified my API like this:

    const getMethod = async function(reqType){
        let req;
        if(!reqType){
            req=server+":"+port;
        }
        else{
            req=`${server}:${port}/${reqType}`;
        }
        const response = await fetch(req,{mode:'cors'})
    
        return response.json();
    }
    

    Which returns a Promise and then I modified the script at my html like this:

            window.onload = async function(){
                const res = await getMethod();
                console.log(res);
                classifyInfo(res);
                console.log("Get Information");
            }
    

    resolving the promise and getting my good, coming-from-node-server, data.

    I like to use resolve, reject, but I suppose a try/catch will do the same.

    Reply

Leave a Comment