我有两个函数返回诺言,我分别将它们使用:
getLocal().then(...)
和
getWeb().then(...)
但是现在我遇到了一个奇怪的问题:
1)我需要第三个函数,该函数兑现承诺
2)该函数必须首先检查getLocal()
是否具有数据。如果有,那么退还该诺言。
3)如果getLocal()
没有数据,则返回getWeb()
希望我更清楚...有帮助吗?
答案 0 :(得分:4)
async function f() {
return await getLocal() || await getWeb();
}
答案 1 :(得分:3)
您可以使用Promise.all
Promise.all([getLocal(), getWeb()]).then(([local, web]) => {
return local|| web
});
答案 2 :(得分:2)
希望我正确理解了您的问题,我认为它应该很简单:
async function combinedResult() {
return (await getLocal()) || (await getWeb());
}
const combined = await combinedResult();
答案 3 :(得分:1)
我无法想象您正在存储原始布尔值。这是您想要做的基于 promise 的版本。
const hasData = local => {/* your code to check if local has data */}
const getLocal = () => {/* get from local */}
const getWeb = () => {/* get from web */}
getLocal().then(local => hasData(local) ? local : getWeb())