mardi 22 octobre 2019

How to get fetches in a Promise.all to await the result of another fetch statement that is conditional

I have a conditional fetch that determines a part of a URL for a subsequent fetch, bit I only want it to run in certain conditions. The following is not waiting and runs the 'try' right away:

async function fetchURLs() {
let sessionWait = false;
  if ((check1 === true) && (check2 === false)) 
        {sessionWait = await getURL();
        } else {sessionWait = true}

  if (sessionWait === true){ 
  try {
    var [a, b, c] = await Promise.all([

      fetch(dataUrl, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: 'post',
      }).then((response) => response.text()).catch(error => console.log(error.message)),
      fetch(settingsUrl).then((response) => response.text()).catch(error => console.log(error.message))

  } catch (error) {
    console.log(error);
  }

});
}

async function getURL(){

   let subDomain = 'a';
   fetchAdd = "https://" + subDomain + ".dexcom.com/ShareWebServices/Services/General/LoginPublisherAccountByName"
  await fetch(fetchAdd, {
    method: 'POST',  
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
   }).then((res) => res.json()).then((SessionData) => dataUrl = "https://" + SessionData).catch(error => console.log(error.message));

 return true;
}

Aucun commentaire:

Enregistrer un commentaire