检查一个对象是否是一个有前途的函数
Checking if an object is a promising function
在protractor.js,
我有 promise/defer 的功能。例如
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'
&&
'与之前的?
或者是否有非typeof
函数,例如...
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。
在protractor.js,
我有 promise/defer 的功能。例如
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'
&&
'与之前的?
或者是否有非typeof
函数,例如...
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。