What is the best method to implement a promise return in AngularJS?

Here is an example code snippet:

var lastTime = '';
$scope.loadEvents = function () {
   var items = listEvents();
    items.then(function (data) {
        lastTime = data;
    });
};


$scope.openModal = function (data) {
     //I need to access lastTime here;   
};

When a button is clicked, the openModal() function is called and I want to ensure that data is returned.

I am thinking that in order to achieve this, I must return a promise from the loadEvents() function.

Do you have any suggestions?

Answer №1

To ensure that the data from an asynchronous operation is retrieved correctly, it is recommended to return the promise from the source and use it in the OpenModal function. This approach guarantees that whenever the modal is clicked, the data will always be returned without any synchronization issues.

$scope.loadEvents = function () {
   var items = listEvents();
   return items.then(function (data) { //Ensure loadEvents returns a promise
       return data;  //Return the data after any necessary processing
    });
};

$scope.openModal = function (data) {
     $scope.loadEvents().then(function(data){ //
         lastTime = data;
     });
};

To prevent multiple simultaneous calls before receiving a response from the server, you can reuse the same promise created earlier.

 var _cachedPromise;
 $scope.loadEvents = function () {
   var items = listEvents();

    if(_cachedPromise) return _cachedPromise;

    _cachedPromise = items.then(function (data) { //Ensure loadEvents returns a promise
       return data;  //Return the data after any necessary processing
    });

    _cachedPromise.finally(function(){
        _cachedPromise = null;
    });

   return _cachedPromise;
};

It is advisable to handle this promise caching logic in the service rather than the controller...

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 on sorting a FileList object selected by a directory picker in JavaScript/TypeScript

I need to filter or eliminate certain files from a FileList object that I obtained from a directory chooser. <input type="file" accept="image/*" webkitdirectory directory multiple> Within my .ts file: public fileChangeListener($event: any) { let ...

Setting a custom background image in a Bootstrap modal

When users visit my website, I want to enhance their experience by using a background image in my bootstrap modal. Despite several attempts, I have been unable to successfully set a background image in the modal. Can anyone provide guidance on this matter? ...

Navigating through different sections of a website using AngularJS routing based on ng-view located

Recently, I started delving into Angular and experimenting with setting up basic routing. On my landing page (currently named index2.html), I have included some .js and .css files, as well as a div with <ng-view></ng-view> to display my content ...

What is the default method for automatically disabling drop down fields?

I've created a script that will gray out a drop-down field if a prior selection wasn't made. Once the appropriate choice is selected, the grayed-out field will become active. My query is, how can I set the drop-down field to be initially grayed ...

How to convert a querydict with multiple objects into lists

When I send an array of JavaScript objects to a Django view via AJAX, the object structure is as follows: [{'oid':'id1','oiid':'iid1'},{'oid':'id2','oiid':'iid2'}] This is ho ...

What is the best method for importing a single module within a monorepo project using JavaScript and NPM?

I've organized my codebase into a monorepo with the following structure: ➜ yw git:(master) tree . ├── package.json ├── packages │ ├── common │ │ ├── package.json │ │ ├── src │ │ │ ├─ ...

Tips for removing cookies with Javascript after an allotted period of time

I need to remove a specific cookie value that I set after a certain time period. For example, I want the cookie to be deleted after 10 seconds. function fullday() { document.getElementById("res").innerHTML="1 day"; document.cookie="day="+1; do ...

Eliminate any undefined data in the popup map of Javascript

I am working with JSON data that is being displayed in a pop-up on a map. In cases where there is missing data (Visibility), the word undefined appears in the pop-up. Is there a way to remove the undefined text so that it does not show up in the pop-up? ...

Transform an SVG file into a PNG format using the image's path as the guideline

Can an SVG image be converted to the PNG format within an angular project? I came across a library called save-svg-as-png, but it requires the id of an svg canvas. However, in my code, I am using the img tag to display the SVG image: <img src="path/to ...

Update your Electron application with the npm update command

I have recently published an app on a local npm repository, and this particular app serves as a crucial dependency for my second electron application. The electron app I am working on is structured around node_modules/my-first-app/dist/index.html. I am w ...

The mystery of the missing body in a Node.js post request

I have developed an API in Node.js and I am facing an issue with the POST method where the body is coming as undefined. How can I extract the value passed using fetch? Node.js Code------------------------------------------ const express=require('expr ...

Tips for retrieving nested data objects from a JSON API on the web

Below is the provided API link - I attempted to utilize this jQuery script in order to collect data for each state individually for my project. However, I am facing difficulties accessing the information with the code provided below. $.getJSON('http ...

Show the content of a list from a different URL on a webpage using HTML with the

My current task involves retrieving JSON data using Jquery and then displaying the names in a simple HTML list. Typically, the JSON files I work with have a straightforward format like: [ {a:1,b:2},{a:3,b:4}] However, this time, the JSON file is hosted ...

When the template is loaded, the AngularJS radio button does not reflect the checked status based on

Is there a way to automatically check the correct radio button based on the value of fc.confidence when the template initially loads? Even when the value of fc.confidence is None, the code provided below does not select either radio button. div.contai ...

Easiest method to incorporate dynamic content into a statically generated page using Node.js with Express

Running a static webpage from Node.JS using the Express webserver: app.use('/', express.static('public')); What is the most efficient way to add dynamic content, like a list of items retrieved from a database, to this page? One option ...

Send data via AJAX requests to store in the database

I am currently working on a project to develop a platform where users can add scenes to YouTube videos by providing the scene name and start & pause time. I have already created an interface that allows users to input this information, but I am now lookin ...

Viewing saved information prior to saving - JavaScript

I'm looking for a solution to allow users to preview captured records before they are inserted. Any suggestions on how to achieve this? HTML.html <form id="view" method="POST" class="formular"> <label>Name</label> ...

Remove all $.ajax requests from content that has been loaded using $.ajax in jQuery

I'm currently working on a page where users can click a link to load content using $.ajax into a designated container div. However, I've encountered an issue with multiple clicks causing an increase in the number of $.ajax requests and resulting ...

Is it necessary for React to have NodeJS in the frontend environment?

As a newcomer to the world of React, I am eager to create a simple hello world example from scratch. While most tutorials provide a standard setup involving nodeJS and npm, I decided to take a different approach: app.js var reactElement = React.createEle ...

Personalized Pinnacles featuring Angular directive elements displayed on a Bing Maps interface

I've implemented the Bing Maps AJAX Control to showcase a map, and I've crafted an Angular directive specifically for the Pushpins intended on the map: app.directive('myPin', function(){ return { restrict: 'E', ...