简体   繁体   English

处理javascript中的promise

[英]handle promises in javascript

I am having trouble when using promise. 使用诺言时遇到麻烦。 my controller is 我的控制器是

angular.module('shoppingPad').controller('customerCtrl', customerCtrl);
function customerCtrl($scope, customerService){

    $scope.addCustomer=function() {
        alert("inside add Customer function");
        var customer={
            name: $scope.name,
            number: $scope.number
        };
         customerService.addCustomer(customer).then(function(response){
          console.log(response);
         },
         function(error){
            console.log(error)
         });
}

this is my service 这是我的服务

angular.module('shoppingPad').service('customerService', customerService);
function customerService($q, $http,restService) {
    //this is deferred object which will resolve or resolve the promise
    var deferred = $q.defer();
    //a function to add customer data to backend used service.it takes customer object as paramater.
    this.addCustomer = function(customer) {
  return restService.postRequest('customers/info',customer,function(response){
        deferred.resolve(response.data); 
       return deferred.promise;
    },
    function(error){
        deferred.reject(error);
        return deferred.promise;
    });
};

This is my restService.js 这是我的restService.js

angular.module('shoppingPad').service('restService',restService);
function restService($http){
    //set port number and baseUrl here
    var port=3001;
    var baseUrl="http://localhost:"+port;

//generic getRequest function 


this.postRequest=function(url,data,successCallback,failureCallback){
    $http({
        method:'POST',
        url:baseUrl+"/"+url,
        data:data
    }).then(function(response){
        successCallback(response);
    },
    function(error){
        alert("internal server error");
        failureCallback(error);

    });

};//end of postRequest function
}//end of service

I am getting error in my controller as Error: customerService.addCustomer(...) is undefined. 我在控制器中遇到错误,因为错误:customerService.addCustomer(...)未定义。 if Iam doing wrong please correct me with good code 如果我做错了,请用正确的代码纠正我

The problem in your code is that you are not returning anything from your $http() call in this.postRequest() method. 您的代码中的问题是您没有从this.postRequest()方法中的$http()调用返回任何内容。

Change your method as below: 如下更改您的方法:

 this.postRequest=function(url,data){
    return $http({
             method: 'POST',
             url: baseUrl+"/"+url,
             data: data
           });

 };

Don't pass success and error callbacks in this but just return the promise from this upstream method and handle the promise. 不要在其中传递成功和错误回调,而只是从此上游方法返回promise并处理promise。 Also, since every return of this promise will be a promise in itself you don't need to create a new promise using $q in your customerService . 另外,由于此承诺的每次返回本身就是一个承诺,因此您无需在customerService使用$q来创建新的承诺。 Just return the same promise from postRequest method as below: 只需从postRequest方法返回相同的promise,如下所示:

this.addCustomer = function(customer) {
  return restService.postRequest('customers/info', customer);
}

This way you don't need additional unnecessary promises. 这样,您就不需要其他不必要的承诺。

Now in your controller you can handle the returned promise as below: 现在,在您的控制器中,您可以如下处理返回的promise:

$scope.addCustomer=function() {
  alert("inside add Customer function");
  var customer={
        name: $scope.name,
        number: $scope.number
  };

  customerService.addCustomer(customer)
   .then(function(response){
     console.log(response);
   })
   .catch(function(error){
     console.log(error)
   });
}

Also I have used .catch instead of passing the error callback as second parameter to .then because it has an added advantage of catch ing errors in the success callback along with any errors from returned promise 我也使用了.catch而不是将错误回调作为第二个参数传递给.catch .then因为它具有捕获成功回调中的错误以及来自返回的promise的任何错误的附加优势。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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