我如何判断一个对象是一个角$ Q承诺? [英] How can I tell if an object is an Angular $q promise?
问题描述
我有一个pre-现有的非角API在我的项目库。它有它返回jQuery.Deferred承诺一个 .request
方法。我创建了一个简单的角度服务,包装了 .request
方法,其结果转换成一个角$ Q承诺来代替。它看起来是这样的:
I have a pre-existing non-Angular API library in my project. It has a .request
method which returns jQuery.Deferred promises. I created a simple Angular service which wraps the .request
method to transform its result into an Angular $q promise instead. It looks something like this:
var module = angular.module('example.api', []);
module.factory('api', function(
$q,
$window
) {
function wrappedRequest() {
var result = $window.API.request.apply($window.API, arguments);
return $q.when(result);
};
return {
request: wrappedRequest
};
});
我想编写一个测试以确保该服务是否正常工作。它将提供一个模拟 $窗口
与 API
的要求
方法返回jQuery.Deferred承诺。我需要确保所产生的对象是角$ Q的承诺。
I would like to write a test which ensures that this service is functioning correctly. It will provide a mock $window
with an API
whose request
method returns jQuery.Deferred promises. I need to ensure that the resulting objects are Angular $q promises.
我怎样才能确定一个对象是否是一个角$ Q承诺?
How can I determine whether an object is an Angular $q promise?
对于这个问题给出的例子就足够jQuery.Deferred的承诺和角$ Q承诺加以区分,但理想的,我们可以在一般的识别角$ Q的承诺。
For the example given in this question it would be sufficient to distinguish between jQuery.Deferred promises and Angular $q promises, but ideally we could identify Angular $q promises in general.
推荐答案
一般来说,更好的方法是投你拥有的任何对象成角的承诺。
Generally the better approach is to cast whatever object you do have into an Angular promise.
同化thenables的概念是承诺/ A +规范的一部分。最有希望的库有办法做到这一点。它就是让对承诺的实现和一个统一的API之间的互操作真棒
The concept of assimilating thenables is part of the Promises/A+ specification. Most promise libraries have a way to do this. It's what allows for awesome interop between promise implementations and a uniform API.
对于这一点,$ Q使用。当
:
For this, $q uses .when
:
包装一个对象可能是一个值或一个(第三方)当时能承诺到$ Q承诺。当你正在处理的对象可能会或可能不会是一个承诺,或者承诺来自于不可信任的来源,这是很有用的。
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.
它使用thenables的理念,以非可靠的承诺转化为$ Q承诺。
It uses the concept of thenables to convert a 'non trusted' promise into a $q promise.
因此,所有你需要做的就是
So all you have to do is
var p = $q.when(value); // p is now always a $q promise
// if it already was one - no harm
这篇关于我如何判断一个对象是一个角$ Q承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!