0

I need to execute a chain of promises with a timer for external requests. As someone suggested in the similar thread I used async/await and rewrite it a bit:

class myClass{
    constructor(symbols){
     this.downloadCsv(symbols)
    }

    // async/await method executing requests with timer
    static async downloadCsv(symbols){
        const result = [];
        symbols.forEach(symbol => {
           await timer(1000)
           result.push(await this.downloadOneCsv(symbol['symbol']) )
        }
        return result
    }

    downloadOneCsv(symbol){
    //request goes here
    }
}

While executing a code above I keep receving an error message suggesting that async/await is not valid:

     await timer(1000)
     ^^^^^

SyntaxError: await is only valid in async function

How can I fix it?

andrzej541
  • 919
  • 1
  • 9
  • 21

1 Answers1

1

First of all you are not able to use timer in a forEach because of its nature and calling callback functions as much as amount of your array elements in stack. That timer method after adding async keyword to the callback function will get fired just once and other times will get skipped. I suggest use for of loop on that array.

static async downloadCsv(symbols){
    const result = [];
    for (const symbol of symbols) {
       await timer(1000)
       result.push(await this.downloadOneCsv(symbol['symbol']) )
    }
    return result;
}

Old One:

const timer = ms => new Promise(resolve => setTimeout(resolve, ms));
const arr = [1, 2, 5, 6, 7];

arr.forEach(async item => {
  console.log('Before Timer');
  await timer(1000);
  console.log(item);
});

Fixed One

const timer = ms => new Promise(resolve => setTimeout(resolve, ms));
const arr = [1, 2, 5, 6, 7];

(async () => {
  for (const item of arr) {
    await timer(1000);
    console.log(item);
  }
})();
Alireza Kiani
  • 410
  • 1
  • 5
  • 11