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(...);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…