Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...