Async initiator in Javascript

Viewed 219

It's been frequently used that we initiate a variable synchronously.

const x = call_a_sync_function();

But when the initiator becomes async, there would be a problem.

const x = await call_an_async_function(); // SyntaxError: Unexpected reserved word

I tried anonymous async initiator, it's not perfect.

let x;
(async () => x = await call_an_async_function())();
export function func() {
  call(x); // x would be undefined if func() is called too early.
}

Then I tried to export the function in the anonymous async initiator, failed again.

(async () => {
  const x = await call_an_async_function();
  export function func() { // SyntaxError: Unexpected token export
    call(x);
  }
)();

So, is there a better solution?

3 Answers

This is a special case of this problem. Asynchronous code can't be turned into synchronous. If a promise is used in an export then a promise should be exported:

const x = call_an_async_function();
export async function func() {
  call(await x);
}

Once there are promises, promise-based control flow is propagated everywhere the order of execution and error handling should be maintained, up to entry point:

import { func } from '...';

(async () => {
  await func();
  ...
})().catch(console.error);

Wrap everything into an async function,

async function getX() => {let x = await call_an_async_function()); return x;}
function func() {
  call(x); // x would be undefined if func() is called too early.
}

async function main(){
   let x = await getX()
   func();
}

main()

Once top-level-await becomes part of ecmascript ( proposal), you wont have to wrap your await in async function and can use await at top level.

Now, we can use --harmony-top-level-await with node.

Related