I need some help here. 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 Im 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. Im 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()? Let me know if I need to post the node server code.TY.
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"
CodePudding user response:
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.