Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

javascript - Way to find if function will return promise

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(...);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...