1

Can you make a function wait until a variable is set by another function? This is my example:

function setvar(){
 //some process that may take a while
 myvar = 'value';
}

const promise1 = new Promise((resolve, reject) => {
  resolve(myvar);
});

promise1.then((value) => {
  console.log(value);
});

this doesnt seem to work, the function begins even if the variable is not ready. What should I do? I dont want settimeout or setinterval because I dont know exactly how long it is going to take each time.

gobler
  • 95
  • 1
  • 6
  • what's the purpose of `setvar` function that you never call? - it should return a promise then all would be good - then you don't need `promise1` ... just `setvar().then(console.log)` – Bravo May 13 '22 at 02:41
  • Fix the `setvar` function so that it takes a callback or returns a Promise, then you can chain off of it easily – CertainPerformance May 13 '22 at 02:41
  • setvar is called on page load but even if setvar finishes its execution it is no guarantee that the variable is going to be set by then. – gobler May 13 '22 at 02:45
  • You need `setVar` (or whatever it is calling it) to call a callback or `resolve()` a promise. Pass the `'value'` as an argument. Do **not** set a global variable. – Bergi May 13 '22 at 03:51
  • thank you but as I said, resolving the function doesnt mean the variable gets set on time for the other function to execute since the variable gets its values from a webpage and between the time it takes to load and then too populate there is not enough time. – gobler May 13 '22 at 05:40
  • This is a duplicate in the way "How do I bake cupcakes?" is a duplicate of "How do I use an oven?". – toddmo Feb 23 '23 at 04:33

1 Answers1

0

In the promise you'll need create a loop that would check if variable was set:

var myvar;
function setvar(){
 //some process that may take a while
 myvar = 'value';
}

const promise1 = new Promise((resolve, reject) => {
  const loop = () => myvar !== undefined ? resolve(myvar) : setTimeout(loop)
  loop();
});

promise1.then((value) => {
  console.log(value);
});


setTimeout(setvar, 2000);
vanowm
  • 9,466
  • 2
  • 21
  • 37
  • cant be done without settimeout? – gobler May 13 '22 at 02:48
  • Not unless function that changes the variable returns a promise – vanowm May 13 '22 at 02:51
  • cant I make it so it returns the variable as a promise? – gobler May 13 '22 at 02:56
  • is variable global? or do you have access to the function that sets the variable? – vanowm May 13 '22 at 02:56
  • yes, the variable is declared globally as an empty array and then on load setvar() fills it up. – gobler May 13 '22 at 03:11
  • TypeScript async/await: `export const waitForValue = async (context: any, property: string) => await new Promise((resolve, reject) => { const loop = () => context[property] !== undefined ? resolve(context[property]) : setTimeout(loop, 100) loop() }) // await waitForValue(this, 'wallpaperDirectory')` – toddmo Feb 23 '23 at 04:46