简体   繁体   中英

How to use promises correctly with callback function

I've this service, it returns a list of students asynchronously using callback:

    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 

My old way to use it in controller:

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

This works for me, but now i want to use some best practices. I need to resolve the result in the route before coming to the controller, here what i did:

.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();
        }
    }
})

The alert is returning data from the route successfully but not from the controller - i get an undefined in the controller:

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

Any help will be appreciated!

You should always return a promise to resolve functions, and, when creating a promise of your own, you should resolve it with the data you need to pass along with 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(sts);
            });
            //})
            //defer.resolve();
            return defer.promise
        }
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM