Having trouble with Async queries

I’m playing around with retool and I have a pretty basic flow write now to create a new user (athlete). It’s linked only to a google sheet right now for simplicity.

From a modal, I take the data and want to do a few things synchronously (not really important here for DB schema). However, I can’t seem to get the results from the queries I am waiting on.

The javascript code looks like this:

const getCurrentDatetimeUtcForDBFunction = async () => {
  await getCurrentDatetimeUtcForDB.trigger();
  return getCurrentDatetimeUtcForDB.data;
};

// TODO: Check errors on promises
const getAthleteIdOrNull = async (email) => {
  await getAthleteByEmail.trigger({
  additionalScope: {
    email
  }});
  
  console.log('getAthleteByEmail.data' + JSON.stringify(getAthleteByEmail.data));
  
  if (getAthleteByEmail.data.length > 0) {
    return getAthleteByEmail.data[0].id
  } else {
    return null;
  }
};

// TODO: Check errors on promises
const createNewAthlete = async (newAthleteData) => {
  postAthlete.trigger({
    additionalScope: {
			newAthleteData
    },
    onSuccess: function(data) {
    	console.log('Successully created new athlete with Id: ' + newAthleteData.id);
  	},
    onFailure: (error) => {
      console.error('Unable to create new athlete for: ' + error);
    },
  });
};

// TODO: Check errors on promises
const doesSubscriptionAlreadyExist = async (trainerId, athleteId) => {
  await getSubscriptionByTrainerAndAthlete.trigger({
    additionalScope: {
      'trainer_id': trainerId,
      'athlete_id': athleteId
  }});

  return getSubscriptionByTrainerAndAthlete.data.length > 0;
};

// TODO: Check errors on promises
const createNewSubscription = async (newSubscriptionData) => {
  postSubscription.trigger({
    additionalScope: {
			newSubscriptionData
    },
    onSuccess: function(data) {
    	console.log('Successully created new subscription with Id: ' + newSubscriptionData.id);
  	},
    onFailure: (error) => {
      console.error('Unable to create new subscription for: ' + error);
    },
  });
};

const onNewAthleteFormSubmit = async (submittedAthleteData) => {
  const createdAt = await getCurrentDatetimeUtcForDBFunction();

  const newAthleteEmail = submittedAthleteData.new_athlete_email_input;
  let newAthleteId = await getAthleteIdOrNull(newAthleteEmail);

  if (!newAthleteId) {
    newAthleteId = getLastAthleteId.data[0].id + 1;
    await createNewAthlete({
      'id': newAthleteId, 
      'name': submittedAthleteData.new_athlete_name_input,
      'country': submittedAthleteData.new_athlete_country_input,
      'city': submittedAthleteData.new_athlete_city_input,
      'province': submittedAthleteData.new_athlete_province_input,
      'email': newAthleteEmail,
      'created_at': createdAt
    });
  }


  const trainerId = parseInt(urlparams.hash.trainer_id);
	const subscriptionAlreadyExists = await doesSubscriptionAlreadyExist(trainerId, newAthleteId);
  if (subscriptionAlreadyExists) {
    throw new Error('The athlete subscription already exists'); 
  }

  const newSubscriptionId = getLastSubscriptionId.data[0].id + 1;
  await createNewSubscription({
    'id': newSubscriptionId, 
    'trainer_id': trainerId,
    'athlete_id': newAthleteId,
    'pricing_plan_id': submittedAthleteData.new_athlete_pricing_plan_input,
    'status': submittedAthleteData.new_athlete_status_dropdown,
    'created_at': createdAt
  });
  
  new_athlete_modal.close();
}

onNewAthleteFormSubmit(new_athlete_form.data);

and is triggered off of the form submission. Everything works as expected but it seems that my queries don’t get updated in the actual request. For example, I have a very simple “query” for getting the current UTC time string for the google doc DB for now:

return new Date().toLocaleString('utc', { hour12: false }).replace(',', '');

which is referenced in the function with the getCurrentDatetimeUtcForDB. What I find is odd is that I’m not getting the current time results right away. So on the first form submission, the created_at time is null. On the second submission, it is using the value from the first submission. It seems the query is still being down async even though in my function I am specifically awaiting on the result (eg):

const createdAt = await getCurrentDatetimeUtcForDBFunction();

I am not super familiar with js and assume I am probably missing something. Any help would be greatly appreciated!! :slight_smile:

Hey Brandon!So this gets a little tricky- high level, all Run JS Code queries are run on an entirely separate, sandboxed iFrame than the retool app itself. This means that all values from your app are passed in at the moment that the query is triggered.So if query1.data = 123 initially, and it is always equal to the foobar value passed in :

console.log(query1.data)
query1.trigger({additionalScope: {'foobar':456}})
console.log(query1.data)
then this actually evaluates the same as this, since the query1.data variable is defined at the beginning
console.log(123)
query1.trigger({additionalScope: {'foobar':456}})
console.log(123)
To have this behave more like you'd expect, you would need to define new variables was get defined asynchronously.
console.log(query1.data) // logs 123
const promise = Promise.resolve( query1.trigger({additionalScope: {'foobar':456}}) )
console.log(promise) // logs 456

Ahh thank you! Got it all working now. I appreciate the help and the quick reply!