5

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?

1
  • 1
    Not really. You have to go asynchronous all the way up. Commented Oct 30, 2018 at 5:51

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, that is the perfect solution!
1

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.

1 Comment

It's better than the anonymous async initiator. But it still needs to call "getX()" manually. When the number of files of async initiators increases, there would be numerous "getX()" functions which need to be exported and called in "main". Is it possible to eliminate the manual call?
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.