Home > other >  Breaking async/await flow
Breaking async/await flow

Time:04-14

I am writing testcases for selenium in our own test automation framework. Because i want to know what our framework is doing, i have added some logging to the console that will also be added to our test report.

For this i have written the following function

async error(message?: any, indent?: boolean) {
    const datetime = timeUtils.generateTimestampForLogging();
    indent = indent == undefined ? true : indent;

    this.mycon.info(`${CYAN}${indent ? '\t' : ''}${datetime} :: ERROR :: ${message} ${RESET} `);

    if (this._world != undefined) {
      await this._world.attach(`<span style="color:forestgreen;">${datetime} :: ERROR :: ${message}</span>`, 'text/html');
    }
  }

To attach the data to the test report, i have to use async/await. However, i don't want to make the 'error' function asynchronous since i also use it in places that expect a non-promise return value. Like here enter image description here Is there a way to keep the 'error' function non-async and still wait for the 'attach' call?

Like this? enter image description here

CodePudding user response:

When using fs with promises, use the fs.promises object rather than the callback-based API:

async function createIfNotExists(path: string): Promise<void> {
    try {
        // instead of passing an error object to a callback, this throws on error
        await fs.promises.access(path);
    } catch {
        // here, we know an error occurred with the access
        await fs.promises.mkdir(path, { recursive: true });
    }
}
  • Related