What is the correct way to utilize $q's constructor syntax in conjunction with Angular's $http service's config.timeout feature?

Now that the Promise is officially specified, I am looking to convert the promise creation in the snippet below from $q.defer() to using the

$q(function (resolve, reject) {})
constructor syntax. Can anyone help with this?

// To ensure only the most recent $http callback gets invoked,
// cancel any ongoing $http request
var canceller;
function getThing(id) {
  if (canceller) canceller.resolve();
  canceller = $q.defer();

  return $http.get('/api/things/' + id, {
    timeout: canceller.promise
  });
}

(For reference, according to $http docs, timeout is "… in milliseconds, or a promise that should abort the request when resolved.")

Answer №1

My approach would be as follows:

let cancelFunction = null;
function fetchItem(itemId) {
  if (cancelFunction) cancelFunction();
  return Promise.resolve($http.get('/api/items/' + itemId, {
    timeout: new Promise(function(resolve) {
      cancelFunction = resolve;
    })
  }));
}

I assume you wouldn't have utilized cancelFunction.reject anyway, so it's better to hold onto the resolve function itself for future use.

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

Upon establishing a connection in Express JS, Socket.io will execute multiple times

I found a helpful repository on GitHub for integrating socket.io, you can check it out here. My goal is to create a countdown timer that sends updates to the client every second. I am using setInterval on the server side to achieve this functionality. The ...

Is there a one-liner to efficiently eliminate all instances of a specific sub-string from an array using the filter

In search of a solution to filter an array and eliminate all instances of substrings, similar to removing entire strings as shown below: const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"] x= x.filter(i ...

Sharing data between app.js and client-side files in Node.js: How to do it effectively?

I have a question about passing a value from my Node.js app.js file to my client-side JavaScript file. Here is my app.js file: var express = require('express'); var app = express(); var port = process.en ...

Angular date filter: Display month in the current time zone format

My date is in ISO-8601 format: overview.startTime = "2017-05-09T08:00:00Z" I am trying to display it on my webpage using the code below: Dagens arbetspass {{overview.startTime | date:'dd-MMM'}} However, the output shows "Dagens arbetspass 09-M ...

Help kids find solutions

Here is the HTML code I am working with: <div class = "touch" onclick="do(this)"> <span>text01</span> <span>text02</span> <span>text03</span> <span>text04</span> <div class = "findMe">a ...

Contrasting the lib and es directories

I am seeking clarity on my understanding. I am currently working with a npm package called reactstrap, which is located in the node_modules folder. Within this package, there are 4 folders: dist es lib src I understand that the src folder contains the s ...

Enhancing the PreLoadMe script to cater to browsers that have JavaScript disabled

Greetings everyone, I have implemented this script (created by Niklaus Gerber) successfully, but there is a small issue. Upon setup, it initially covers the entire page with a div using CSS styles. Then, the script reveals the fully loaded site as intended ...

Updating the @mui/x-data-grid table dynamically upon fetching new data

Seeking assistance regarding updating data in the DataGrid component from the @mui/x-data-grid module within a React application. Specifically, I am facing challenges in refreshing the table after retrieving data from an API using react-query. Despite succ ...

Develop an Innovative Data-Driven Application using AJAX Technology

After inputting an artist's name and clicking on the button, I expect to receive a visually appealing list of their songs. I am encountering the following issue: Whenever I hit the button, no results are being returned, and I am unsure of the reaso ...

The issue arises due to conflicting indent configurations between eslint and @typescript-eslint/indent

Currently, I am using eslint and prettier in a TS express application. I am trying to set the tab width to 4, but it appears that there is a conflict between the base eslint configuration and the typescript eslint. When looking at the same line, this is w ...

Rails not receiving JSON data

I am attempting a straightforward ajax call in Rails 4, but encountering issues with retrieving the json response. Below is the script I'm working with: $(document).on "submit", "form[name=upvote-form]", -> form = $(this) $.post "/vote", $(th ...

The clear feature within Angular Material's AutoComplete component is causing a blockage for all the DOM elements

It's a rare situation, but when using the autocomplete feature in this specific way, all DOM elements get blocked and interaction with elements on the page becomes impossible. Here is the HTML code snippet: <md-autocomplete style="background-col ...

Implementing an ajax search functionality

I am currently working on implementing an AJAX search feature into my project. The application initially displays all client data in a table on the webpage. When something is typed into the search bar, I want the search results to be shown instead of all ...

Exploring Variable Naming in Angular with Dynamic Scope

Is there a way to avoid using large IF statements in my controller when working with fields/models that have similar logic but different scope variable names? I'm looking for a solution to dynamically append numbers to the scope variable names in Angu ...

JavaScript Variable Naming ConventionEnsuring correct spelling in variable names is essential

While I may not be a JavaScript expert, I have a question about its dynamically typed nature. We are all aware that JavaScript (node.js) is a dynamically typed language where we can easily assign values like: someObject.attr = 123; However, due to the la ...

Mastering the art of reading arrays in Json with JavaScript

Recently, I stumbled upon some Json data that looks like this: var x = { "array1":"['x1','x2']", "array2":"['a1', 'a2']" } My mission is to display each element of the array individually: x1 x2 a1 a2 However, wh ...

The functionality of V-model is hindered when implementing Bootstrap Tokenfield

While working with Vue and Bootstrap Tokenfield, I encountered an issue where v-model was not functioning as expected. Let's say I have the following array: index variant_options 1 aaa 2 sss If I remove index 1, the result of inde ...

`A dynamically captivating banner featuring animated visuals created with JQuery`

I am currently in the process of designing a banner for the top of my webpage, but I have yet to come across any code that meets all my requirements. To provide clarification, I have attached an illustration showcasing what I am aiming to achieve. 1) The ...

Tips for efficiently populating a MongoDB database for end-to-end testing

After following the setup process outlined in this guide: https://medium.com/developer-circles-lusaka/how-to-write-an-express-js-server-using-test-driven-development-921dc55aec07, I have configured my environments accordingly. Utilizing the config package ...

Comparing jQuery Elements

As per the jQuery documentation, it is stated that "Not All jQuery Objects are Created ===." The documentation also points out an important detail about the unique nature of each wrapped object. This uniqueness holds true even if the objects were created ...