AngularJS data retrieval timeout function

After reading this response, I am currently in the process of developing a service that can provide data even if the request fails due to timing out.

this.getStatus = function()
    {
        var timeoutPromise = $timeout(function () {
            canceler.resolve();
            console.log("Timed out");
        },250);

        var canceler = $q.defer();

        $http.get("data.js", {timeout: canceler.promise} ).success(function(data){
          console.log(data);

          $timeout.cancel(timeoutPromise);

          return data;
        });
    };

This is how the Service with the $http request is called

var promises = [
    firstService.getStatus(),
    secondService.getStatus(),
    thirdService.getStatus()
];

$q.all(promises)
   .then(function (serviceResults) {
        //process Data in case of success
        console.log("Result First Service: "+ serviceResults[0]);
        console.log("Result Second Service: "+ serviceResults[1]);
        console.log("Result third Service: "+ serviceResults[2]);
    })
    .catch(function() {
        //process Mock data in case of Failure
    });

The objective is to retrieve the actual response data if the request succeeds or display mock data if there is a timeout.
How can data be returned when a request times out?

Answer â„–1

Here are some steps you can take:

this.checkStatus = function()  {
    var deferredCheck = $q.defer();
    var timeoutPromise = $timeout(function () {
        deferredCheck.resolve(
          // SIMULATED DATA GOES HERE
        );
        console.log("Request timed out");
    }, 250);

    $http.get("data.js", {timeout: canceler.promise} ).then(function(data){
      $timeout.cancel(timeoutPromise);
      deferredCheck.resolve(data);
    }).catch(deferredCheck.reject);

    return deferredCheck.promise;
};

This method ensures that if the request is successful, it will resolve with the response data. If a timeout occurs, it will resolve with simulated data instead. If any other error arises before the timeout, the promise will be rejected with the corresponding error.

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 saving data after reading lines in Node.js

I am working on a project where I need to read data from an external text file into my function. How can I efficiently store each line of the file as a separate variable? const fs = require("fs"); const readline = require("readline"); const firstVariable ...

Dealing with cascading menu in knockout viewmodel

I have incorporated knockoutjs into my current project. One particular requirement I encountered was the need to create a nested menu within my viewmodel. Here is how I implemented it: self.menu = [ { name: 'Services', su ...

I am experiencing some issues with React Router V4's functionality

I am currently developing a web application where I intend to showcase user details on the same page using routers when they are clicked. Below is my index.js file: window.React = React; render(<div> <Menu/><MainMenu/><App/>&l ...

Can you interact with a node within an Electron application even if the node integration feature is not enabled?

I have an electron app created with vanilla electron. (using npx create-electron-app ......) Can I use const electron = require("electron"); with nodeintegration:true? The library I'm using does not support nodeintegration:true, but my scr ...

Discovering the method to access a local function within a static function in Javascript ES6 (ES2015) or Typescript

Is there a way to access the non-static "foo2" method from inside the static "bar" method? So far, I'm only able to access the "foo1" and "foo3" methods. Can anyone provide guidance on how to achieve this? let foo1 = () => { alert('foo1†...

NodeAutoComplete: Enhanced Autocompletion for Node.js

I am attempting to utilize autocompletion of a JavaScript file with Node.js and Tern. However, the documentation for Ternjs is incredibly lacking. const tern = require("tern"); const ternServer = new tern.Server({}); const requestDetails = { "qu ...

Rhino's env.js causes the anchor element's pathname to be undefined

Encountered an issue that appears to be related to how anchor tags are implemented in Rhino. Despite using env.js, there might be a configuration error causing the problem. The issue arises when writing unit tests for code designed for an angularjs applic ...

Why does my Visual Studio Code always display "building" when I launch an extension?

https://code.visualstudio.com/api/get-started/your-first-extension I followed a tutorial to create a hello world extension. Why does my VSCode always display 'building' when I run the extension? Executing task: npm run watch < [email p ...

Evolution of ReactJS state over time

When working with React, I wanted to increment a state variable called progressValue by 0.1 every 500 ms until it reaches 100. Here's what I initially tried: const [progressValue, setProgressValue] = React.useState<number>(0) const tick ...

Issue with docker-composer module not being detected specifically on windows operating system

We are currently in the process of setting up a container running node.js with docker (specifically docker-compose, as we plan to incorporate mongodb later). Our approach involves copying the package.json in the Dockerfile and then creating a volume mount ...

Refresh needed for Material UI styles to load correctly in Next JS

UPDATE: Reproducible issue https://github.com/ganavol409/next-material-ui-classes-bug Issue seems to be related to Higher Order Components and importing useStyles from Material UI Implemented Solution: https://github.com/mui-org/material-ui/blob/master/ ...

Several different factors

I need to develop a form that allows users to edit existing comments. The form will display a textarea containing the old comment text and a submit button. My goal is to send the newComment data via ajax to another script. However, I am facing an issue w ...

What is the reason for the jQuery plugin not being applied after replacing the page content with an Ajax response?

At the moment, I am utilizing jQuery ajax to dynamically add content to my website. Additionally, I have incorporated the jquery.selectbox-0.6.1.js plugin to enhance the style of select boxes on the page. The plugin successfully styles the select boxes up ...

Using JavaScript to Transfer Data Between Web Pages

For our landing page, we're planning to incorporate two levels of questions for the respondents. Initially, the respondents will be asked to choose up to four interest tracks using checkboxes. Once they have made their selections, they can proceed to ...

Validation of the existence of a MongoDB user

I'm currently working on implementing a sign-up form using Mongo, Node.js, and Express.js. I've managed to successfully insert a document into the users collection for a new user. However, I now need to set up validation to check if a user alread ...

Ways to troubleshoot and resolve the jQuery error with the message "TypeError: 'click' called"

I am currently developing a project for managing Minecraft servers, focusing on a configuration panel. I have set up a form that users need to fill out in order to configure the settings and send the values using Ajax. However, I encountered an error: Type ...

Sequentially iterate through elements based on their Data attributes

Assume you are working with HTML elements like the ones shown below <span class="active" data-id="3"> Test 3 </span> <span class="active" data-id="1"> Test 1 </span> <span class="activ ...

Whenever I try to upload a file using ajax in MVC, I consistently encounter a null Request.Files in action side

I am facing an issue with uploading an image using ajax mode in MVC. I have tried a method where everything seems to work fine in the JavaScript code - it gets the formdata and sends the ajax request to the controller correctly. However, in my controller, ...

Exploring the importance of the scope in an AngularJS directive and its role within the linker function

Can you explain the purpose of the scope parameter within the link property of a directive definition object? Does it define the scope for the specific instance of the directive or is it a global scope for all instances? ...

The JavaScript function Date().timeIntervalSince1970 allows you to retrieve the time

For my React Native app, I currently set the date like this: new Date().getTime() For my Swift App, I use: Date().timeIntervalSince1970 Is there a JavaScript equivalent to Date().timeIntervalSince1970, or vice versa (as the data is stored in Firebase clo ...