【发布时间】:2013-12-21 21:27:29
【问题描述】:
我正在制作一个将函数作为作用域参数的指令 (scope: { method:'&theFunction' })。我需要知道该方法返回的结果是否是一个角度承诺(如果是的话,解决方案会发生一些事情,否则它会立即发生)。
现在我正在测试foo.then 是否存在,但我想知道是否有更好的方法。
【问题讨论】:
标签: angularjs
我正在制作一个将函数作为作用域参数的指令 (scope: { method:'&theFunction' })。我需要知道该方法返回的结果是否是一个角度承诺(如果是的话,解决方案会发生一些事情,否则它会立即发生)。
现在我正在测试foo.then 是否存在,但我想知道是否有更好的方法。
【问题讨论】:
标签: angularjs
您可以使用$q.when 将对象包装为一个promise(无论它是否存在)。然后,你可以确定你总是在处理一个承诺。这应该会简化处理结果的代码。
$q.when 的文档是 here with $q。
【讨论】:
$q.when。然后任何调用者都会知道期待一个承诺。
正如 Davin 所说,Angular 的 when() 是一个不错的选择。
如果这不能满足您的需求,那么 Angular 的 internal way of checking(它在 when 中使用它)非常接近您正在做的事情:
var ref = function(value) {
if (value && isFunction(value.then)) {
// Then this is promise
}
【讨论】:
then 属性,而该属性恰好是一个函数。跨度>
(isObject(value) || isFunction(value)) && isFunction(value.then)
@kayakDave,感谢您指导正确的地方。
when(value, [successCallback], [errorCallback], [progressCallback]); Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
$q.when(value).then(function (data) {
//this helps me to bind data from $resource or $http or object
}
检查这个fiddle
【讨论】:
$q.when() 答案似乎是大多数用例的最佳答案,我使用 instanceof 作为我的答案。
if(buttonData instanceof $q) {
buttonData.then(function(actions) {
$scope.buttonActions = actions;
});
} else {
$scope.button = buttonData;
}
或者,以下 IF 也可以,但我最终选择了上述解决方案。
if(Object.getPrototypeOf(buttonData) === $q.prototype) {
【讨论】: