JavaScript中带有条件if语句的嵌套fetch()函数

fslejnso  于 2022-12-02  发布在  Java
关注(0)|答案(2)|浏览(148)

我有一个运行fetch()的函数,在fetch调用的最后,它会记录到控制台。
我想有条件地在第一个fetch函数结束之前添加第二个fetch函数。它也会记录到控制台。
我很难确定如何确保第一个日志等待第二个获取完成,并在实际记录之前记录其数据(无论它是否需要运行)。我已经能够通过几个else语句来做到这一点,但我希望避免重复。
编码笔@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();
xpcnnkqh

xpcnnkqh1#

您可以使用await关键字暂停**alwaysRuns()函数的执行,直到第二次fetch()调用完成。下面是alwaysRuns()**函数的更新版本,它可以完成此操作:

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

await关键字用于暂停**alwaysRuns()函数的执行,直到fetch()调用完成并且它返回的承诺得到解决。这确保了第二个fetch()调用在最后一个console.log()**语句执行之前完成。

zzwlnbp8

zzwlnbp82#

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

相关问题