When a timeout is triggered, the AngularJS Promise is not being cancelled

In my endeavor to incorporate a simple timeout feature into my promise, I set out with the intention that if I do not receive a response within 1 second, the request should be terminated. The code should not hang for a response nor execute any code intended for success. Despite its apparent simplicity, this code is failing to function as expected. Here's what I have:

var canceler = $q.defer();
var timeoutPromise = $timeout(function() {
    canceler.resolve(); //abort the request when timed out
    console.log("Timed out");
    }, 1000);
$http.put(PutUrl, PurDataObject, {timeout: canceler.promise})
  .then(function(response){
        // this section should never be reached if the response exceeds 1 second
});

Any assistance on this matter would be highly valued. My AngularJS version is 1.5.5.

Answer №1

Avoid needlessly using $q.defer() when the $timeout service already provides a promise:

var timeoutPromise = $timeout(function() {
    console.log("Time's up");
    return "Time's up";
}, 1000);

$http.put(NewUrl, NewDataObject, {timeout: timeoutPromise})
  .then(function(response){
        // this section will not be reached if the response takes longer than 1 second
});

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

Exploring the methods for monitoring multiple UDP ports on a single address in Node.js within a single process

I am currently working on developing a Node.js application to manage a small drone. The SDK provides the following instructions: To establish a connection between the Tello and a PC, Mac, or mobile device, use Wi-Fi. Sending Commands & Receiving Responses ...

Enhance results by combining data from user input with data retrieved asynchronously from server-side APIs

In the process of developing a web application, I am facing a challenge. There is an input field where users can enter a number and next to it, I want to display the double of that number as the output. While this can be easily achieved using client-side J ...

Having trouble with the active class in vue-router when the route path includes "employees/add"?

I'm currently developing a project using Vue and implementing vue-router for navigation. A peculiar behavior occurs when the route changes to /employees - only the Employees menu item is activated. However, when the route switches to /employees/add, b ...

How to Retrieve URL Before Closing a jQuery Window Using window.open()?

Is it feasible to retrieve the URL of a window.open window after triggering a window.close event when the user clicks the close button? How can I obtain the last URL visited right before the window closes? ...

Angular 6 - Outdated Functions

I'm having trouble updating the request options as they are now deprecated. I can't seem to locate the alternative option for this. Can anyone offer some assistance? import { Injectable } from '@angular/core'; import { HttpClient } fr ...

Encountering an error message while trying to use `npm i`

I am attempting to set up the environment in order to run tests on JavaScript. I am using Windows 10 and Python 2.7. However, when I input the command 'npm -i', I receive an error message: https://i.stack.imgur.com/j2WXE.jpg To try and resolve ...

Tips for efficiently delivering the create-react-app index file from your server

I have encountered a challenge in my development work with create-react-app. I am looking to serve the index.html file from the backend initially, but I am facing difficulties in achieving this goal. The main reason behind this desire is to customize the ...

Express.js: Communicating with internal microservices

I'm still learning about node.js, express.js and REST APIs. Here's the situation I'm facing: I have a requirement to retrieve user information from my database (using mongoDB) in various scenarios. What would be the recommended approach i ...

How to showcase the data retrieved via BehaviorSubject in Angular

I've been working on retrieving data from an API using a service and passing it to components using BehaviorSubject in order to display it on the screen: Here is the service code snippet: @Injectable({ providedIn: 'root', }) export clas ...

Sort the data by name rather than using the default JSON/C# format

On my webpage, I am displaying product data that is being called in the form of a JSON object in the JavaScript file: _loadAll: function (callback) { $.ajax({ 'type': 'GET', 'timeout': 5000, ' ...

The data is not being successfully transmitted to the controller method through the AJAX call

In my JavaScript file, I have the following code: $(document).ready(function () { $('#add-be-submit').click(function (event) { event.preventDefault(); $.ajax({ type: 'POST', url: '/snapdragon/blog/new&apos ...

Getting access to scope variables in an Angular controller written in ES6 style can be achieved by using

In my new Angular project, I decided to switch to using ES6 (Babel). However, I encountered an issue where ES6 classes cannot have variables. This led me to wonder how I could set my $scope variable now. Let's consider a simple controller: class Mai ...

Can someone guide me on the proper implementation of the 'useEffect' hook in React version 18?

I'm currently working on a project following a YouTube tutorial that uses React 17, while I'm using React 18. Everything has been going smoothly so far, but I've hit a roadblock with formatting animated text. The specific task I'm stuck ...

Ways to update on the status of uploading a video on YouTube

I am currently developing an ASP.NET Web API integrated with Angularjs for client-side programming. The main feature of my application is the ability for users to upload and watch videos. In order to achieve this, I am planning to utilize the YouTube API f ...

How to print a Base64 encoded file with the Print.js library

I am facing an issue with printing a Base64 file. Despite my efforts, the file does not print as expected. function convertToBase64() { var selectedFile = document.getElementById("inputFile").files; if (selectedFile.length > 0) { var fi ...

Is there a way I can utilize canvas to overlay one image onto another?

Is there a way to merge one image into another by using a transparent box? It's not just about copying and pasting an image into another. I also want to know how to transform the image to fit perfectly within the other image. For example, similar to ...

Create 3000 unique squares using a procedural generation method

Looking to build a widget that consists of 3000 squares, but creating them manually would be extremely time-consuming. Does anyone have advice on how to efficiently generate the class .square 3000 times? Additionally, I need to have the ability to customiz ...

Color-Thief Node plugin reported an issue: "The provided image has not finished loading."

While working in Node/Express, I attempted to utilize the npm package color-thief to extract the dominant color from an image. Unfortunately, it failed with the error message stating that the "image given has not completed loading". The intriguing part is ...

What is the best way to swap out a div element with a text area when I press a button, all

I recently used a Fiddle found at http://jsfiddle.net/GeJkU/ function divClicked() { var divHtml = $(this).html(); var editableText = $("<textarea />"); editableText.val(divHtml); $(this).replaceWith(editableText) ...

When utilizing the post method with fetch to send data, an empty object is returned

Here is my code snippet for handling the addEventListener for the click event export const showTicket = async function() { try { // FETCHING USER DATA const response = await fetch("/api/v1/users/me"); const data = await response.json(); ...