【问题标题】:Chaining promises with parameters?用参数链接承诺?
【发布时间】:2014-10-30 19:13:18
【问题描述】:

我想知道 AngularJS 中是否有以下内容的糖速记:

$scope.parseSomeString = function (str) {
    console.log(str);
    // ...
};

someService.fnA($scope.arg1) // fnA doesn't return anything
    .then(function () {
        return someService.fnB($scope.arg2, $scope.arg3()) // fnB returns some, e.g. string
    })
    .then($scope.parseSomeString); // this shorthand is great!

我想做的是这样的:

someService.fnA($scope.arg1)
    .then(someService.fnB($scope.arg2, $scope.arg3())) // but of course, this just calls the function; not good
    .then($scope.parseSomeString); // this shorthand is great!

有什么方法可以将参数$scope.arg2$scope.arg3() 绑定到fnB

【问题讨论】:

  • 你也可以装饰 $q 并为其添加一个.fcall 构造

标签: angularjs promise q angular-promise


【解决方案1】:

您可以使用function.bind (look at support and shim for older browsers) 传入一个带有参数的绑定函数引用,以便在调用函数时将参数绑定到函数。

someService.fnB.bind(this, $scope.arg2, $scope.arg3);

如果您不需要设置特定的上下文(看起来不需要),您也可以将null 作为第一个参数传递,如果需要,您可以将该上下文作为第一个参数传递.

试试:-

someService.fnA($scope.arg1)
.then(someService.fnB.bind(this, $scope.arg2, $scope.arg3)) // but of course, this just calls the function; not good
.then($scope.parseSomeString); // this shorthand is great!

你也可以使用angular.bind

someService.fnA($scope.arg1)
  .then(angular.bind(this, someService.fnB, $scope.arg2, $scope.arg3))...

同样,您会在您可能已经使用的库中找到类似的方法,例如 Lodash/underscore 有 bind,jquery 有 $.proxy 等。

【讨论】:

  • 嗯,这似乎行得通;我将使用 Lo-Dash 的_.bind。我只希望有一个不需要this的版本。
  • @user2857125 是的,您没有提到您正在使用 lodash/underscore,是的,许多库都有自己的版本。 jquery 有jquery.proxy。每个人都需要一个上下文,因为它专门用于创建绑定函数。
  • @user2857125 看到我的更新角度也有一个版本。你也可以使用它。
猜你喜欢
  • 2016-08-06
  • 1970-01-01
  • 2015-10-10
  • 2019-10-14
  • 2015-04-15
  • 2023-01-27
  • 2015-01-21
  • 2016-01-17
  • 1970-01-01
相关资源
最近更新 更多