简体   繁体   中英

Recursive function in typescript

I have a project in Node JS with Typescript in which I am creating a function to check that a file exists, this check returns a boolean.

I have another function timeOut() to wait a while before checking that it has arrived, when it checks if it is true the process continues, if it is false I need it to check again if the file exists after the defined time

This is what I have:

 function sleepTimeout(interval) { return new Promise((resolve) => { setTimeout(resolve, interval); }); }; async function testData(data) { await sleepTimeout(2000); if (data == false) { console.log('KO') } else { console.log('OK') } } testData(true)

It only does a check, how can I make the function redo the if after the timeOut until the boolean is true

You can use async/await to make sure the function is done before starting again, and a while loop:

async function testData(data) {
  while (!data) {
    await sleepTimeout(2000);
    data = await checkFileExists(); // replace this with your function to check if the file exists
  }
  console.log('OK');
}

testData(checkFileExists());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM