Calling async function from main javascript file

Viewed 42

I want to wait for async testBrowser function to return from my async run() function. I want the run() function to be called immediately, so its in the main Javascript file

async function run() {
tests.forEach(test => {
    var result = await testBrowser(test.id, test.testFunction);
      if (result == true) {
        alert("proceed");
    }
  });
}

(async function() {
  await run();
})();

The error I get is "await is only valid in async functions, async generators and modules". Ive tried to do an async anonymous function that calls my function and itself, which is the solution for the same question (Calling async function in main file), but I keep getting the error.

I also tried turning my javascript file into a module as suggested by the error message by exporting the run() function, but then I get the error "await is a reserved identifier"

export async function run() {
tests.forEach(test => {
    var result = await testBrowser(test.id, test.testFunction);
      if (result == true) {
        alert("proceed");
    }
  });
}

Calling the module:

<script type="module" type="text/javascript">
  import {run} from './detect-headless.js';
</script>

How can i call this function from my javascript file?

1 Answers

The error is caused by your arrow function not being an async function. To fix this, use a for loop instead

async function run() {
  for (var test of tests) {
    var result = await testBrowser(test.id, test.testFunction);
      if (result == true) {
        alert("proceed");
      }
  }
}

await is intended to reduce the amount of callback functions. Avoid using functions like forEach for this same reason.

Edit:

If you intend to do something after all promises, you can store each promise into an array and use Promise.all to combine them into a single Promise. This either fails if any fail or passes if all pass and returns an array with the results.

async function run() {
  var promises = []
  for (var test of tests) {
    promises.push(testBrowser(test.id, test.testFunction))
  }
  var results = await Promise.all(promises)
    if (!results.some(result => !result)) {
      alert("proceed");
    }
}

forEach was added before Promises and does not wait for any returned Promise. In terms of speed, unfortunately either approach would not be any faster at executing tests. Javascript runs in a single linear flow. Promises work by halting execution in one area, in order to do work somewhere else (called co-operative threading).

Related