How to return a promise after checking the result of one promise before calling another promise

Viewed 55

I have two functions returning promises and I'm using them independently as:

getLocal().then(...)

and

getWeb().then(...)

However now I ran into a weird problem:
1) I need a third function that returns a promise
2) The function must first check if getLocal() has the data. If it has, then return this promise.
3) If getLocal() doesn't have the data, then return the promise of getWeb()

Hope I'm clearer... any help?

4 Answers
async function f() {
  return await getLocal() || await getWeb();
}

You can use Promise.all

Promise.all([getLocal(), getWeb()]).then(([local, web]) => {
  return local|| web
});

Hope I understood your question correctly, I believe it should be as simple as:

async function combinedResult() {
  return (await getLocal()) || (await getWeb());
}
const combined = await combinedResult();

I can't imagine you're storing raw booleans. Here is a promise based version of what you want to do.

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())
Related