Mastering the art of utilizing promises effectively in conjunction with callback functions

Currently, I have a service that retrieves a list of students asynchronously using a callback function:

    studentModule.factory('StudentService', function (DB_URL) {
        return {
            getAllStudents: function (callback) {
                var Datastore = require('nedb'),
                    path = require('path');
                db = {};
                db.students = new Datastore({
                    filename: DB_URL + '/students.db',
                    autoload: true
                });
                db.students.find({}, function (err, stds) {
                    callback(stds);
                });
            }; //end return 

Initially, I was making use of this service in the controller in the following manner:

StudentService.getAllStudents(function(sts) {
    $scope.students = sts;
    $scope.$apply();//notify angular about the change
});

While this method has served me well, I now aim to incorporate some best practices. I intend to resolve the result in the route before reaching the controller. Here's how I modified it:

.state('payment', {
    url: '/payment',
    templateUrl: 'frontend/components/payment/views/payment.html',
    controller: 'PaymentController',
    resolve: {
        students: function (StudentService, $q) {
            var defer = $q.defer();
            defer.promise.then(function () {
                StudentService.getAllStudents(function (sts) {
                    alert(JSON.stringify(sts));
                    return sts;
                });
            })
            defer.resolve();
        }
    }
})

Although the alert successfully displays data from the route, it appears as undefined in the controller:

paymentModule.controller('PaymentController', function($scope, students) {
    alert(JSON.stringify(students));

Any assistance on this matter would be greatly appreciated!

Answer №1

It is important to always use promises to handle asynchronous functions. When creating your own promise, make sure to resolve it with the necessary data.

.state('payment', {
    url: '/payment',
    templateUrl: 'frontend/components/payment/views/payment.html',
    controller: 'PaymentController',
    resolve: {
        students: function (StudentService, $q) {
            var defer = $q.defer();
            StudentService.getAllStudents(function (sts) {
                defer.resolve(sts);
            });
            return defer.promise
        }
    }
})

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

Unusual behavior observed when altering properties of checkboxes

Here is the code snippet in question: <table border="1" style="margin:0 auto;"> <tr> <td class="pointer" style="padding: 2px;"><input style="margin-left: 2px;" type="checkbox" name="nuovoCheck" id="newCheckId" value="N" /& ...

Does this task require a high amount of CPU resources for Node.js on the back-end?

I am currently developing an Android app and I am faced with a decision on whether to utilize node.js or PHP for the back-end. The task at hand involves users inputting query parameters, such as zip codes, which are then used to perform database queries ...

How can I transfer an instance of a class to dataTransfer.setData?

So I created a new instance of a class: let item = new Item(); Next, I attempted to serialize the item and add it to dataTransfer for drag and drop functionality: ev.dataTransfer.setData("info", JSON.stringify(item)); At some point, I need to retriev ...

Tips for accessing nested JSON values using Selenium

Here is a JSON snippet to work with: "ACCOUNT": { "AmountDue": "$36,812.99", "OutstandingBalance": "$27,142.27", "StatementTotal": "$9,670.72", "StatementDate": "12/6/2018", "DueByDate": "12/23/2018", ...

Implementing Image Data in AngularJS: A Guide to Binding Images to IMG Tags

Allow me to explain the problem further. I am retrieving a user's profile picture by calling an API that returns image data, as shown in the screenshot below https://i.stack.imgur.com/t8Jtz.jpg https://i.stack.imgur.com/pxTUS.png The reason I canno ...

I prefer not to have my preceding component re-rendered in React

I'm currently working on developing a user interface for a search engine using elasticsearch within React. One issue I'm facing is with the Pagination technique - when a user clicks on a result and then navigates back to the list of results, it r ...

What is the best way to control the amount of rows displayed in my gallery at any given time?

I need help with customizing my gallery that is dynamically generated from a directory using PHP. My goal is to display only 2 rows of 4 images each, totaling 8 images, with a "show more" button for loading additional rows. How can I set a limit on the n ...

jQuery AJAX POST Request Fails to SendIt seems that the

The issue I am experiencing seems to be directly related to the jQuery $.ajax({...}); function. In PHP, when I print the array, I receive a Notice: Undefined index. I would greatly appreciate any advice or guidance on this matter. <script> $(docume ...

The input tag loses focus after its value is updated using a class method in Angular 8.x

Currently, I am working on integrating a credit card payment method and formatting its number through specific methods. Here is how it is done: HTML <div class="form-group" *ngFor="let formField of cardFields; let cardFieldIndex = index;"> ...

Socket connection issue causing Laravel Event not to display on registration

I want to display notifications for new users who have registered on my website, so that existing logged-in users can see messages like "blabla has registered...". To achieve this, I first created an Event class along with a channel setup: class UserSign ...

Having trouble getting the AJAX script to change the background in Internet Explorer?

I'm currently experiencing an issue with an ajax script. Here is the code I am using: <script type="text/javascript"> $(document).ready(function() { $('#savecolor').click(function(){ var myVar = 'data= ...

Issue: [unresolved] Provider not recognized: $resourseProvider <- $resourse <- Phone Angular factory

I'm encountering an issue with injecting a resource. Error: [$injector:unpr] Unknown provider: $resourseProvider <- $resourse <- Phone Here is my code: index.html <script src="bower_components/angular/angular.js"></script> < ...

The module "angular2-multiselect-dropdown" is experiencing a metadata version mismatch error

Recently, I updated the node module angular2-multiselect-dropdown from version v3.2.1 to v4.0.0. However, when running the angular build command, I encountered an "ERROR in Metadata version mismatch for module". Just to provide some context, I am using yar ...

Using a global variable in Vue and noticing that it does not update computed variables?

Currently, I'm in the process of developing a web application and have begun implementing authentication using firebase. Successfully setting up the login interface, my next step is to propagate this data throughout the entire app. Not utilizing Vuex ...

Tips for concealing a div when the mouse is moved off it?

My goal is to create a simple hover effect where hovering over an image within a view filled with images displays an additional div. This part works as expected. However, I'm facing issues when trying to hide the same div when the user moves out of t ...

Waiting to run a function until a specified function has finished its execution

I have a piece of code that needs to address synchronization issues related to the execution order of MathJax functions. Specifically, I need to ensure that all the MathJax operations are completed before running the setConsoleWidth() function. What is t ...

Ensure that the form is validated even when setState is not executed immediately

I am currently working on a form in React and I am facing an issue with validation. When the Submit Form button is clicked without filling in the input fields, an error should be displayed. This part is functioning correctly. However, even when the fields ...

The JSON POST Method is not allowed for a Self-Hosted WCF REST service

After encountering countless "WCF" questions online, I am starting to believe that finding a solution is nearly impossible. Can someone prove me wrong? My current situation involves working with a Self Hosted WCF Service where endpoints are defined progra ...

Understanding Mongodb: the process of populating a schema that is referenced within another schema using an API

Looking to make adjustments to my Api in order to populate a referenced schema. Here's the schema I am working with: export const taskSchema = new Schema ({ user:{ type: String, required: true }, project: { type ...

Exploring the capabilities of xhr2 using pure javascript

Currently, I am attempting to utilize xhr2 in order to read through a json file. Despite my efforts in researching various methods to accomplish this task, none have proved successful thus far. The function featured below my require statements is the one t ...