Skip to content
Advertisement

Why function is executed although await is used?

I have used await keyword in the main function to wait for the completion of async function call to poll() and yet the function call to my_plot is made before the completion of the poll() function.

JavaScript

Code output:

JavaScript

Expected:

JavaScript

Advertisement

Answer

Don’t use setTimeout directly from within an async function. Instead, use a Promise-based wrapper.

It’s surprising that modern ECMAScript doesn’t come with an in-box Promise-based version of setTimeout, but it’s straightforward to implement:

JavaScript
  • Then you can rewrite your poll function with a “real” while loop, like so (below).
  • I think your poll function should return a true/false value to indicate success or failure to the caller, if you ever need to.
  • Consider using typeof instead of less safe checks like Object.keys(data).length – or at least using a typeof check before using Object.keys.
    • Though annoyingly typeof null === 'object', so you will always need a !== null check, grumble
    • As an alternative, consider having your own type-guard function (yes, I know this isn’t TypeScript), that way you get even stronger guarantees that data contains what you need (as JS does not have static type checking).
JavaScript

Note that if you intend to catch errors thrown by getData you should use a minimally scoped try instead of having more logic in there, as generally you won’t want to catch unrelated errors.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement