如何处理不总是返回承诺的函数? [英] How to handle functions that do not always return a promise?
问题描述
当一个函数并不总是返回promise时,处理情况的最佳方法是什么?我的实际代码太复杂了,无法解释,但是问题的实质归结为检查条件,并根据条件我要么返回一个局部变量,要么需要发送一个ajax请求. 像这样:
What is the best way to handle situations when a function does not always return a promise? My actual code is too complicated to explain but the essence of the problem boils down to checking a condition and depending on it I either return a local variable or need to send an ajax request. Something like this:
function example(value){
if(!value){
return $http.get('www.example.com');
}
else {
return "Your value is "+value;
}
}
有没有一种方法可以检查该函数返回的值是否是一个承诺并且需要解决?也许还有另一种方法来处理这种情况?谢谢您的投入!
Is there a way to check if the value returned by the function is a promise and needs to be resolved? Or maybe there is another approach to handle such situations? Thank you for your input!
推荐答案
虽然您可以测试返回类型是否为Promise
:myValue instanceof Promise
,但最好编写始终返回Promise
,或者可能需要返回值,只需将Promise.resolve()
与值一起使用:
While you can test to see if the return type is a Promise
: myValue instanceof Promise
, it is better to simply write functions that always return a Promise
. That makes them consistent and much easier to deal with. In your example where you may need to return a Promise
for an async function, or may need to return a value, just use Promise.resolve()
with the value:
function example(value) {
if(!value) {
return $http.get('www.example.com');
} else {
return Promise.resolve('Your value is ' + value);
}
}
这样,您不必担心它会得到什么回报,并且始终可以以一致的方式对其进行处理.
That way, you don't have to worry about what it gives back and can always deal with it in a consistent way.
这篇关于如何处理不总是返回承诺的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!