返回内部$ http承诺

时间:2019-06-04 05:52:58

标签: javascript angularjs angular-promise

我有两项服务:

ProductService

CartService

还有一个控制器:

ShoppingController

ShoppingController需要从服务器下载购物车。为了使CartService能够做到这一点,ProductService必须首先下载产品。

ProductService.js

ProductService.DownloadProducts = function(){
          if(alreadyHaveDownloadedProducts){                   
              return {
                  success: function (fn) {
                      fn(products);
                  }
              };
          }else{
              if(getProductsPromise== null){
                  getProductsPromise= $http.post("Api/GetProducts")  
              }
              return getProductsPromise;
          }

CartService.js

CartService.DownloadCart = function(){
    ProductService.DownloadProducts().success(function(){
          if(alreadyHaveDownloadedCart){   
              //Dont need to go to server                
              return {
                  success: function (fn) {
                      fn(cart);
                  }
              };
          }else{
              if(getCartPromise == null){
                  getCartPromise = $http.post("Api/GetCart")  
              }
              return getCartPromise; //<= The promise I actually want to return
          }
    })
}

ProductService.DownloadProducts

ShoppingController.js

CartService.DownloadCart().success(function(){DisplayCart()});

到目前为止,这种方法效果很好,因为如果已经在其他页面上调用了ProductService,则无需返回服务器。购物车服务也是如此。问题是我目前无法返回getCartPromise,因为直到异步GetProducts返回之前,它才被创建

是否可以构造此结构,以便我可以在保留良好的.success()语法的同时将内部的Promise返回给ShoppingController?

1 个答案:

答案 0 :(得分:0)

我的方式类似于您的方式,但是我没有保存一些alreadyHaveDownloadedCart(布尔标志),而是将自己的promise进行了缓存,然后将其返回。

我正在将对服务类中数据的promise进行缓存,然后将其返回(如果存在),否则将初始化服务器调用。

类似的东西:

class ProductService {
  constructor() {
    this.productsPromise = null;
  }

  DownloadProducts() {
    if(!this.productsPromise) {
      this.productsPromise = $http.post('Api/GetProducts');

      this.productsPromise.then(products => this.products = products);
    }

    return this.productsPromise.then(() => this.products);
  }
}

class CartService {
  constructor(ProductService) {
    this.ProductService = ProductService;
    this.cartPromise = null;
  }

  DownloadCart() {
    return this.ProductService.DownloadProducts().success(() => {
      if (!this.cartPromise) {
        this.cartPromise = $http.post('Api/GetCart');
        this.cartPromise.then((cart) => {
          this.cart = cart;
        });
      }

      return this.cartPromise.then(() => this.cart);
    });
  }
}