javascript - How to use promises correctly with callback function -
i've service, returns 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 use in controller:
studentservice.getallstudents(function(sts) { $scope.students = sts; $scope.$apply();//notify angular change });
this works me, want use best practices. need resolve result in route before coming controller, here 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 returning data route not controller - undefined in controller:
paymentmodule.controller('paymentcontroller', function($scope,students) { alert(json.stringify(students));
any appreciated!
you should return promise resolve functions, and, when creating promise of own, should resolve data need pass along 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 } } })
Comments
Post a Comment