Home > database >  Nested fetch() functions with conditional if statement in JavaScript
Nested fetch() functions with conditional if statement in JavaScript

Time:12-02

I have a function that runs a fetch() and at the very end of the fetch call it logs to the console.

I want to conditionally add a second fetch function before the end of the first. It also logs to the console.

I'm having trouble working out how to ensure the first log waits for the second fetch to complete and log its data before actually logging (whether or not it actually needs to run). I've been able to do this with several else statements, but I'd like to avoid the repetition.

Codepen @ https://codepen.io/cfxd/pen/bGKmRZj

function alwaysRuns() {
  fetch('https://api.spacexdata.com/v4/launches/latest')
    .then(result => result.json())
    .then(resultJson => {
      const rocketId = resultJson.rocket;
      const rocketName = resultJson.name;
      if(rocketName.includes('Crew')) {
        fetch(`https://api.spacexdata.com/v4/rockets/${rocketId}`)
          .then(rocketResponse => rocketResponse.json())
          .then(rocketJson => {
            console.log('This fetch might not happen, depending on the conditional')
        });
      }
      console.log('this should always log last whether the conditional causes the second fetch to run or not!');
  });
}
alwaysRuns();

CodePudding user response:

You can use the await keyword to pause execution of the alwaysRuns() function until the second fetch() call completes. Here's an updated version of your alwaysRuns() function that does this:

async function alwaysRuns() {
  // Make the function asynchronous so we can use `await`
  const result = await fetch('https://api.spacexdata.com/v4/launches/latest');
  const resultJson = await result.json();
  const rocketId = resultJson.rocket;
  const rocketName = resultJson.name;

  if(rocketName.includes('Crew')) {
    const rocketResponse = await fetch(`https://api.spacexdata.com/v4/rockets/${rocketId}`);
    const rocketJson = await rocketResponse.json();
    console.log('This fetch might not happen, depending on the conditional')
  }

  console.log('this should always log last whether the conditional causes the second fetch to run or not!');
}

alwaysRuns();

The await keyword is used to pause execution of the alwaysRuns() function until the fetch() call completes and the promise it returns is resolved. This ensures that the second fetch() call is completed before the final console.log() statement is executed.

CodePudding user response:

Use await

function alwaysRuns() {
  fetch('https://api.spacexdata.com/v4/launches/latest')
    .then(result => result.json())
    .then(async resultJson => {
      const rocketId = resultJson.rocket;
      const rocketName = resultJson.name;
      if(rocketName.includes('Crew')) {
        await fetch(`https://api.spacexdata.com/v4/rockets/${rocketId}`)
          .then(rocketResponse => rocketResponse.json())
          .then(rocketJson => {
            console.log('This fetch might not happen, depending on the conditional')
        });
      }
      console.log('this should always log last whether the conditional causes the second fetch to run or not!');
  });
}
alwaysRuns();

or even better

function alwaysRuns() {
  fetch('https://api.spacexdata.com/v4/launches/latest')
    .then(result => result.json())
    .then(resultJson => {
      const rocketId = resultJson.rocket;
      const rocketName = resultJson.name;
      if(rocketName.includes('Crew')) {
        return fetch(`https://api.spacexdata.com/v4/rockets/${rocketId}`)
          .then(rocketResponse => rocketResponse.json())
          .then(rocketJson => {
            console.log('This fetch might not happen, depending on the conditional')
        });
      }
    }).then(() => {
    console.log('this should always log last whether the conditional causes the second fetch to run or not!');
  });
}
alwaysRuns();
  • Related