Leveraging JavaScript promises to execute a function only once

  var dataFetch= $q.defer();

  function fetchData(){
    return dataFetch.promise;
  }

  (function getData(){
    setTimeOut(
       function(){
          myPromise.resolve("data");
       }
      ,1000);
  })();

   fetchData().then(function(){alert("use old fetched data");});

The code above shows how "dataFetch" is defined outside the scope of the "getData" function, ensuring that a new promise is not created with each invocation of "getData".

"getData" will only be called once, and "dataFetch" will retain the data from the initial call without being updated.

Is this considered a promise anti-pattern? If so, what is the correct way to execute an asynchronous function just once?

Answer №1

Let me present it in a different way:

let infoPromise = new Promise((resolve) => {
    setTimeout(() => {
        resolve("information");
    }, 2000);
});

function getInfoPromise() {
    return infoPromise;
}

getInfoPromise().then(() => {alert("displaying old information");});

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

Issue with Next.js's notFound() function not properly setting the 404 HTTP Header

Our decision to use Nextjs was primarily driven by the need for SSR and SEO optimization. We rely on an external REST API to fetch data on the front end, but we face challenges when trying to pre-render certain pages and display a proper 404 Not Found head ...

Guide to customizing the Autocomplete jQuery plugin to mimic Google's result replacement feature

I have implemented the jQuery plugin Autocomplete like Google for two form fields - foo and bar (which is dependent on the value of foo): $(function() { $("#foo").autocomplete({ minLength: 3, limit: 5, source : [{ u ...

Can one extract the content from a secure message received from a Telegram bot?

Currently, I am utilizing the sendMessage() function with protected_content: true in order to prevent Telegram users from forwarding my bot's messages to others. Prior to implementing this setting, the text below was easily copyable. However, after e ...

What could be causing the issue with the array.push method not functioning

i have come across this piece of code function fetchImagesList(errU,errorsList) { if(errU) throw errU; var directories=new Array(); var sourceDir=''; var destinationDir=''; if(errorsList==&a ...

What is the process for linking an HTML document to another HTML document within a div using jQuery?

Check out my HTML code: <!DOCTYPE html> <html> <head> <title>Hilarious Jokes!</title> <meta charset="utf-8"> <link href="final%20project.css" rel="stylesheet"> <script src=" ...

What causes AJAX to disrupt plugins?

I am facing a challenge with my webpage that utilizes AJAX calls to load content dynamically. Unfortunately, some plugins are encountering issues when loaded asynchronously through AJAX. I have attempted to reload the JavaScript files associated with the ...

Examining the version of a node module installed in the local environment and comparing it

One of the reasons I am asking this question is because I have encountered challenges while collaborating with other developers. At times, when other developers update node module versions, I forget to install these new modules after pulling the latest co ...

Can one wait for a class in JavaScript?

When using the keyword await, JavaScript will wait until a promise settles and then return its result. I have observed that it is also possible to use await with a function. var neonlight = await neon(); But, can you await a class? For example: var ne ...

Attaching to directive parameters

I've been working on creating a draggable div with the ability to bind its location for further use. I'm aiming to have multiple draggable elements on the page. Currently, I've implemented a 'dragable' attribute directive that allo ...

Passing a JavaScript variable to PHP resulted in the output being displayed as "Array"

After sending a JavaScript variable with the innerHTML "Basic" to PHP via Ajax and then sending an email with that variable, I received "Array" instead of "Basic". This situation has left me puzzled. HTML: <label class="plan-name">Plan name: <b ...

What is the optimal method for transmitting both an image and JSON data to my express server?

Hey there! So I've set up a MongoDB database and I'm using Mongoose to work with it. Here's the model I have for my product: const productSchema = new Schema({ name: { type: String, required: true}, description: { type: String, required ...

Retrieving information from deeply nested JSON structures within React components

I am developing a web application that focuses on searching and displaying movie information. One of my challenges is accessing nested objects like "principals" from the same endpoint that contains the main object "title". Upon fetching the JSON response: ...

HTML stops a paragraph when encountering a script within the code

Everything in my code is working correctly except for herb2 and herb3, which are not displaying or utilizing the randomizer. I am relatively new to coding and unsure of how to troubleshoot this issue. <!DOCTYPE html> <html> <body> ...

What is the best way to utilize jQuery in order to present additional options within a form?

Let's consider a scenario where you have an HTML form: <form> <select name="vehicles"> <option value="all">All Vehicles</option> <option value="car1">Car 1</option> <option value="car2">Car 2< ...

Troubles arise when trying to load AngularJS using RequireJS within the application

I am currently developing a NodeJS application that utilizes AngularJS for its front-end. Additionally, I am integrating RequireJS to handle the loading of JavaScript dependencies and then initialize the Angular app. Here is my approach: Inside my HTML fi ...

Issue with styled-components not being exported

Issue: ./src/card.js There was an import error: 'Bottom' is not exported from './styles/cards.style'. card.js import React from 'react' import { Bottom, Color, Text, Image } from "./styles/cards.style"; fu ...

Sending information upwards within an onClick event in a React component

Just starting out with React/ES6 and diving into creating my first components. Currently, I have a PuzzleContainer component that houses a Puzzle component responsible for displaying images. The container component triggers an AJAX call to fetch data on wh ...

Increase the identification of HTML element with jQuery

I've encountered an issue while trying to increment the id of 2 HTML elements, hwAddition and itemNumber, upon a button click event. The HTML code in question is as follows: <div id="hwAddition"> <div id="itemNumber" s ...

Could someone review my coding syntax in JavaScript for utilizing indexOf, split, and looping through multiple inputs to paste the splits?

As someone who is self-taught and codes part-time as a hobby, I am currently working on building a JavaScript/jQuery tool. This tool will allow users to copy rows or columns from Excel and paste them into an online HTML form consisting of a grid of <tex ...

The visibility of a ThreeJS mesh disappears when its center moves out of the camera's view

Struggling to develop a map featuring various meshes, I've encountered an issue where meshes disappear when the center of the mesh is out of the camera view. Check out this gif demonstrating the problem: Currently using THREE.WebGLRenderer 71, is th ...