如何将承诺解析为视图中的对象?

How do I make a promise resolve as an object in the view?

我正在尝试将第三方库包装到 return 一个对象,该对象解析为一个可以在视图中显示的对象,类似于 $resource() 的工作方式。我知道我可以在承诺上手动执行 .then() 然后设置值,但我希望结果无缝 return 类似于我可以做的:

this.Value = $resource("/someresource").get();

我如何将下面的 SomeThirdPartyFunction() 更改为 return 在视图中解析的对象。

这是我正在尝试做的一个例子:

angular.module('testApp', []).controller('TestController', function ($timeout, $q) {
    var TestController = this;
    var SomeThirdPartyFunction = function () {
        var Deferred = $q.defer();
        var Promise = Deferred.promise;

        $timeout(function () {
            Deferred.resolve("abcd");
        }, 3000);

        return Promise;
    };

    TestController.Value = SomeThirdPartyFunction();

    /* I don't want to do this:
    SomeThirdPartyFunction().then(function(Value) {
      TestController.Value = Value;
    });*/
});

这是一个笨蛋:https://plnkr.co/edit/HypQMkaqXmFZkvYZXFXf?p=preview

我见过的每个使用 promises 的例子都只是包装 $http 调用,但我还没有看到任何调用第三方库的例子 return promises 解析为对象。

来自AngularJS document

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.

因此,您可以这样代替 return 承诺:

  var SomeThirdPartyFunction = function() {
    var getAComplextObject = function() {
      return {
        number: 42,
        method: function() {
          return this.number + 1;
        }
      };
    };

    var returnValue = {};

    $timeout(function() {
      console.log("Resolved!");
      Object.assign(returnValue, getAComplextObject());
    }, 1000);

    return returnValue;
  };

您可以将其包装在一个承诺中,并使该承诺成为 return 值的一部分,这样您就可以使其成为可用的(也称为承诺)

引擎盖下,$resource uses angular.copy

function myResourceGet(params) {
    var emptyObj = {};
    emptyObj.$resolved = false;
    emptyObj.$promise = $http.get(url, {params:params})
      .then(function(response) {
        angular.copy(response.data, emptyObj);
    }).finally(function() {
        emptyObj.$resolved = true;
    });
    return emptyObj;
}

来自文档:

angular.copy Overview

Creates a deep copy of source, which should be an object or an array.

  • If a destination is provided, all of its elements (for arrays) or properties (for objects) are deleted and then all elements/properties from the source are copied to it.

$resource 服务仅在数据为对象或数组时有效。它不适用于字符串或数字等基元。