While executing a fetch operation inside a regular function, an Uncaught TypeError occurs with the message: "p1() is undefined." Additionally, the if


function fetchData(){
    let req = fetch("https://ghibliapi.herokuapp.com/people");
    setTimeout(function(){
        if(req.ok){
            return req;
        }
        else{
            return req.statusText;
        }
    },5000);
}

fetchData().then(function(response){
    return response.json();
}).then(function(data){
    console.log(data)
}).catch(function(error){
    console.log("Error", error)
})

setTimeout(function(){
    console.log("Stop")
},6000);

Why does the if-else statement not work in this scenario? It only works when I place the return statement after the else block. Can someone please explain?

Thank you!

Answer №1

If you're tired of relying on timeouts, try implementing async await in your code. It has been a game-changer for me.

async function fetchData(){
    let response = await fetch("https://ghibliapi.herokuapp.com/people");
    if(!response.ok) throw new Error(response.status);
    return response;   
}

fetchData().then(function(data){
    console.log(data);
    return data.json();
}).then(function(){
    console.log("Finished fetching data")
}).catch(function(error){
    console.log("An error occurred:",error.message)
})

Answer №2

Another option is to utilize the fetch method with a return statement

function fetchData(){
     fetch("https://ghibliapi.herokuapp.com/people").then(function(response){
        if(response.ok){
            return response.json();
        }
        else{
            return response.statusText;
        }
}).then(function(result){
    console.log(result)
}).catch(function(error){
    console.log("Error occurred:",error)
})
}

fetchData();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for sending a multipart/form-data request using AJAX

I am facing an issue with the function below. I need to upload multiple files and submit a request via ajax. The content type is currently set as "text/plain;charset=UTF-8" but I want to change it to "multipart/form-data". Can anyone provide suggestions ...

Issue with IPv6 compatibility in Node.js and Selenium causing SocketException due to unavailable protocol family

Encountering this error appears to be unique to when the ios-driver jar is spawned as a Node.js child process. The specific error message is java.net.SocketException: Protocol family unavailable selenium-test.js: var spawn = require('child_process& ...

developing a multimedia player using HTML5

I'm attempting to create a dynamic video "collage" that showcases videos with different aspect ratios in a flexible grid layout. Each row should have videos of the same height, while filling up the horizontal space within a container. With known widt ...

How can we display the data that is causing an error in a fetch call in JavaScript?

when using the fetch statement in JavaScript, like so: fetch (url, data) .then(response => response.json()) .then(data => {}) .catch ((error)=>{console.error ('Error: ',error)}); If an error occurs such as: Error: SyntaxError: JSON.pa ...

Both Google Chrome and Firefox are recognizing the Binance WSS api url as an HTTPS connection

My attempt to execute the code from my Chrome browser was unsuccessful. import io from 'socket.io-client'; const socket = io('wss://stream.binance.com:9443'); socket.on('connect', () => { console.log('binance [so ...

Can a variable name be created using a function input?

It seems like my title might be a bit confusing, but oh well. I'm currently working on developing a game and I have several arrays named things like ItemsInG5Array, ItemsInB2Array. These names correspond to different nodes on the map. What I'm ai ...

"The JavaScript form appears to be malfunctioning as it is unable to calculate results based on

I'm currently working on a JavaScript form that aims to calculate the feeding volume based on various input factors such as feed type, number of feedings per day, target protein intake, current protein intake, and patient's weight. Although the ...

Converting an Excel formula expression into JavaScript code

I am trying to implement the formula from Excel using the JSON object provided below. I have done the computations, but there seems to be an error as the result is not exact. If anyone has any ideas about it, I would appreciate your input. Thank you. I ju ...

Instructions for showing a "read more" and "read less" link when the text goes beyond a

I am pulling paragraph content from the database and displaying only 300 characters on the screen, with a "read more" option for the user to see the rest of the content. However, I am facing an issue where I also need to include a "less" option for the us ...

How can you call a JavaScript function from C# using SignalR?

I have been struggling to get SignalR working despite the many examples available. I am hoping that someone can provide a clear demonstration of how a WebPage with a threaded loop can call a JavaScript method on a page to change a text label or create a po ...

Drop and drag action is preventing the onchange event from being triggered in the form

I have set up a form where users can either 'drag and drop' a file or 'click to upload' it. I want an action to be triggered whenever either of these actions takes place. To achieve this, I am using the onchange event to trigger an act ...

BufferGeometry lines in THREE.js are failing to render when their starting point is outside the view of the camera

Currently, I am in the process of developing a trace-line function for a visualization project that involves transitioning between different time step values. However, I have encountered an issue while using THREE.js's BufferGeometry and the setDrawRa ...

Trigger a click event on a dynamically loaded button

Here's a unique twist to the usual discussions on this topic. I have a dynamically loaded button in my HTML, and I've saved the selector for it. Later on in my code, I need to trigger a click event on this button programmatically. The typical $(& ...

Develop a responsive image component with flexible dimensions in React

I am currently working on developing a dynamic image component that utilizes the material-ui CardMedia and is configured to accept specific height and width parameters. The code snippet I have is as follows: interface ImageDim extends StyledProps { wid ...

Is it possible to connect ng-model with a style tag?

Is it feasible to create a basic template editor using angularjs where an input field with an ng-model can be connected to a style tag to control the css on an entire page rather than applying it to a specific element with inline styling? Could something ...

Is it possible to adjust the height of a panel in Jquery Mobile 1.4.5?

Currently working on a jqm project that is specifically for mobile devices. In this project, I have implemented two panels - one set to push and the other overlay. While one panel is positioned in the left corner of the screen, the other is located in the ...

Obtaining the "category" and "name" from a stacked bar chart using the Highchart OnClick event

I am working with a Highchart stacked chart that includes a category and dataset structured as shown below: categories =["Clark","Steven","Steve","Robert","Max"] series =[{ name: "Wins" data: [0, 0, 0, 0, 0] }, { name: "Losses" data: [0, 0, 0, 0, 0] }, { ...

Error message signaling that the dollar sign symbol is not defined in the Laravel framework

Hello there, I'm currently learning Laravel and following a tutorial on building a student CMS. I have integrated a datepicker and a bootstrap modal that are supposed to pop up when clicking form buttons. However, despite everything appearing correct, ...

Select a random index and modify it until all unique options have been exhausted, then restart the process

My image gallery has 6 slots for images, and I have an array with a certain number of image objects: "src" : { "1x" : "/clients/Logo-1.png", "2x" : "/clients/<a href="/cdn-cg ...

Is it acceptable to use the return value of false in order to resolve the ESLint consistent-return error when working with asynchronous functions

When working with ExpressJS, I encountered a situation where I needed to execute and adhere to ESLint rules in my code. One particular rule that caused an issue is "consistent-return", which flagged the following code snippet: function getUsers( req, res, ...