Dirty Bird Design
Dirty Bird Design

Reputation: 5533

Combine async function result in separate function in more efficient way

I have two async functions, that separately work on their own - they each return data if I call them singularly, but I can't get a result from the second when I try and combine them. Basically I'm pinging an API and if the first function returns a result, use that data. If it returns empty, run the second function and use that data. I'm getting the data through a node proxy (again these work fine separately).

Function 1 that checks for a live event:

async function getLive(){
  const response = await fetch("video-live");
  const getLiveData = await response.json();
  return getLiveData;
}

Function 2 that should run if Function 1 returns empty:

async function getArchived() {
  const response = await fetch("video-archived");
  const getArchivedData = await response.json();
  return getArchivedData;
}

The final function that applies the logic:

function showVideo(getLiveData, getArchivedData) {
  if( (getLiveData) == "" ) {
    console.log('live'+getLiveData);
  } else {
    console.log('no live'+getArchivedData);
  }
}

Then I call them like this:

getLive().then(showVideo);

The above returns 'no live' but not any data from the getArchivedData. How do I combine these in an elegant, efficient way? Can I combine both getLive and getArchived into one function with .then()?

Per @MichaelM's code:

async function getLive(){
  const response = await fetch("video-live");
  const getLiveData = await response.json();
  return getLiveData;
}

async function getArchived() {
  const response = await fetch("video-archived");
  const getArchivedData = await response.json();
  return getArchivedData;
}
async function showVideo() {
  const liveData = await getLive();
  if(liveData == "") {
    console.log('live' + getLiveData);
  } else {
    const archivedData = await getArchived();
    console.log('no live' + archivedData);
  }
}

"Uncaught (in promise) ReferenceError: getLiveData is not defined"

Upvotes: 0

Views: 79

Answers (1)

Michael M.
Michael M.

Reputation: 11070

Try rewriting your showVideo() function to use getLive() and getArchived() directly, instead of passing the results into showVideo(). Like this:

async function showVideo() {
  const liveData = await getLive();
  if(liveData == "") {
    console.log('live' + liveData);
  } else {
    const archivedData = await getArchived();
    console.log('no live' + archivedData);
  }
}

Then you just call showVideo() without the .then() statement.

Upvotes: 2

Related Questions