Home > Software design >  Wait until promise returns true
Wait until promise returns true

Time:08-14

I have a database setup with NodeJS and want to wait until certain table is created before start to create any others. This method tableExists resolves with the status being either true/false, but I want it to wait until it's true only.

const checkTableExists = async () => {
    const exists = await queryInterface.tableExists('Subjects');
    return exists;
}

How can I force a wait until checkTableExists returns true?

CodePudding user response:

Using setTimeout:

const CHECK_INTERVAL = 200; // every 200ms
const checkTableExists = async () => {
   const exists = await queryInterface.tableExists('Subjects');
   if (!exists) {
     return new Promise((resolve, reject) => {
       setTimeout(() => checkTableExists().then(resolve).catch(reject), CHECK_INTERVAL);
     });
   }
   return exists;
}

The solution to something like this is not to keep on waiting. There are other issues that may cause the table not to be created. You may want to adjust the above code to stop checking after it has checked for set number of times, or a duration has passed. Use something reasonable, depending on the environment where your db is running.

CodePudding user response:

Add a delay and repeat:

// Utility function
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

const checkTableExists = async () => {
    while (true) {
        const exists = await queryInterface.tableExists('Subjects');
        if (exists) return true;
        await delay(10000); // Wait 10 seconds before trying again.
    }
}

Although this resolves the promise with true, it is actually is not necessary to return a boolean, as the resolving promise is enough as a signal that the table now exists -- true is the only possible outcome when the promise resolves.

  • Related