在protractor.js中,
我有承诺/推迟的功能.例如
var myFunc = function(_params) {
var deferred = protractor.promise.defer();
/***do magical code things****/
/***wait for other promises***/
/*****deferred.fulfill();*****/
return deferred.promise;
};
我可以使用什么类型的typeof语句组合来检查这个东西(当传递给别的东西时)是否有承诺?
> typeof promiseMaybe ===’function’
> typeof promiseMaybe.then ===’function’
>&&’ed with prior?
或者是否有像…这样的非类型函数
> promiseMaybe.isThenable
> protractor.promise.isThenable(promiseMaybe)
澄清
我有一个接收myFunc作为参数的方法,但是这个方法也可以接收字符串和查找器.我需要知道如何判断参数是否是承诺某事的函数,可能在调用函数之前.
解决方法:
Protractor中有一个辅助方法 – protractor.promise.isPromise():
var el = element(by.css('foo'));
protractor.promise.isPromise('foo'); // false
protractor.promise.isPromise(el); // false
protractor.promise.isPromise(el.click()); // true
量角器直接从selenium-webdriver,here you can find the source code of the method获取此方法:
/**
* Determines whether a {@code value} should be treated as a promise.
* Any object whose "then" property is a function will be considered a promise.
*
* @param {*} value The value to test.
* @return {boolean} Whether the value is a promise.
*/
promise.isPromise = function(value) {
return !!value && goog.isObject(value) &&
// Use array notation so the Closure compiler does not obfuscate away our
// contract. Use typeof rather than goog.isFunction because
// goog.isFunction accepts instanceof Function, which the promise spec
// does not.
typeof value['then'] === 'function';
};
所以基本上,任何带有then方法的对象都被认为是Promise.