1

I need to loop through an array reading each element after some time, the only solution I've seen is to use setTimeOut() in Typescript.

The problem is that I need the function to finish to continue the process.

This is what I currently have:

async function testData() {

  let arrT = ['data1','data2','data3']
  let countReq = 0
  let result = []
  for await (let getA of arrT) {

    countReq++
    setTimeout(async() => {
      result.push(
        `test - ${getA}`
      )
    }, countReq * 1000)

  }

  console.log(result)
  return result;

}
testData()

Now it returns the empty array because the process has not finished, I need to wait and return the array with the complete information

I don't know if using setTimeout() in this case is the best option, I don't know if there is a better way to do this.

mikestr
  • 33
  • 6

1 Answers1

1

You can use a Promise to resolve the task with await. You don't need to provide await after your for key.

function sleepTimeout(interval) {
  return new Promise((resolve) => {
    setTimeout(resolve, interval);
  });
};

async function testData() {

  let arrT = ['data1','data2','data3']
  let countReq = 0
  let result = []
  for (let getA of arrT) {
    countReq++

    await sleepTimeout(1000);
    
    result.push(`test - ${getA}`);
  }

  console.log(result)
  return result;

}
testData()
Nora Söderlund
  • 1,148
  • 2
  • 18
  • I had not tried with promise, I thought that the setTimeOut could do it alone. I need to multiply it by 1000 because if it takes less time the process breaks – mikestr Dec 22 '22 at 23:58