does this promise look correct?

2020-05-09 04:22发布

this seems like it should be delivering data to my scope, but it isn't, is there anything that directly jumps out as wrong with the below code ?

angular.module('Lunch.services', [])
  .factory 'LunchMates', ($q, $http) ->
    LunchMates = 

      getLunchMates: () ->
        d = $q.defer(); 
        $http.get('/lunchers').then (response, status) ->
          if response.status == 200
            d.resolve(response.data)
        return d.promise

    return LunchMates


angular.module('Lunch.controllers', [])
  .controller('LunchCtrl', ($scope, LunchMates) ->
    $scope.lunchers = LunchMates.getLunchMates()
  )

1条回答
姐就是有狂的资本
2楼-- · 2020-05-09 05:14

This code: $scope.lunchers = LunchMates.getLunchMates() sets a promise on the scope, it relies on an old deprecated functionality.

As of version >=1.2, promise unwrapping is deprecated, this is the breaking commit:

This commit disables promise unwrapping and adds $parseProvider.unwrapPromises() getter/setter api that allows developers to turn the feature back on if needed. Promise unwrapping support will be removed from Angular in the future and this setting only allows for enabling it during transitional period.

..........

Previously promises found anywhere in the expression during expression evaluation would evaluate to undefined while unresolved and to the fulfillment value if fulfilled.

..........

BREAKING CHANGE: $parse and templates in general will no longer automatically unwrap promises. This feature has been deprecated and if absolutely needed, it can be reenabled during transitional period via $parseProvider.unwrapPromises(true) api.

You can still enable it with $parseProvider like so:

angular.module('Lunch.controllers', [])
  .config( ($parseProvider) ->
    $parseProvider.unwrapPromises(true)
    $parseProvider.logPromiseWarnings(false)
  )

But it would break in future versions (as mentioned above), so instead do this:

angular.module('Lunch.controllers', [])
  .controller( 'LunchCtrl', ($scope, LunchMates) ->
    LunchMates.getLunchMates().then (data)->
      $scope.lunchers = data
  )

This issue (among some others) is very common, mostly because lots of tutorials & books that new developers find all over the web, was written before version 1.2 and therefore not up-to-date. Always keep yourself up-to-date with the https://github.com/angular/angular.js/blob/master/CHANGELOG.md

查看更多
登录 后发表回答