如何找到函数将返回诺言 [英] Way to find if function will return promise
问题描述
下面我有一个函数返回一个解析 true
的promise。有什么方法可以找出函数是否会返回一个promise?
var myPromiseFunction = function(){
返回Promise.resolve(true)
}
myPromiseFunction()。then(function(value){
console.log(value)// => true
$)
函数mySyncFunction(){
返回hello
}
willReturnPromise(myPromiseFunction)// => true
willReturnPromise(mySyncFunction)// => false
我可以找出一个函数是否会返回一个promise?
否(不是没有实际调用它)。这里最好的办法是依靠命名和API约定的一致性。
只是为了快速证明无法测试返回类型,请考虑以下几点函数:
函数maybeAPromise(){
if(Math.random()< .5){
return Promise.resolve('foo');
} else {
return'bar';
}
}
虽然我个人认为动态语言的生产力优势像JavaScript一样值得他们权衡,不可否认的是编译时类型安全的缺乏是负面类别中的折衷之一。 p据说, Promise.resolve()
很方便,如果您只是想强制结果为 Promise
。例如,
Promise.resolve(maybeAPromise())。then(...);
Below I have a function that returns a promise that resolves true
. Is there any way I can find out if a function will return a promise?
var myPromiseFunction = function(){
return Promise.resolve(true)
}
myPromiseFunction().then(function(value){
console.log(value) // => true
})
function mySyncFunction(){
return "hello"
}
willReturnPromise(myPromiseFunction) // => true
willReturnPromise(mySyncFunction) // => false
Is there any way I can find out if a function will return a promise?
No (not without actually invoking it). Your best recourse here is to rely on consistency in naming and API conventions.
Just for a quick "proof" on the inability to test for a return type, consider the following function:
function maybeAPromise() {
if (Math.random() < .5) {
return Promise.resolve('foo');
} else {
return 'bar';
}
}
While I personally feel that the productivity advantages of dynamic languages like JavaScript are worth their tradeoffs, there's no denying that the lack of compile-time type safety is one of the tradeoffs in the "negative" category.
That being said, Promise.resolve()
is handy if you simply want to force a result to be a Promise
. E.g.,
Promise.resolve(maybeAPromise()).then(...);
这篇关于如何找到函数将返回诺言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!