JavaScript await by default instead of manually
Asked Answered
A

1

3

Async/await are really handy, but I want the opposite of their behavior. Instead of other functions continuing on unless I manually ask them to await a promise, I want functions to yield unless I manually specify that they continue running in parallel.

For instance, this code would print out 1 3 2:

function wait(ms) {
    return new Promise(r => setTimeout(r, ms));
}

async function a() {
    console.log("1");
    await wait(5000);
    console.log("2");
}

a();
console.log("3");

I want it to print out 1 2 3, with function a() not actually returning until I've waited 5 seconds and 2 has been printed. I'm making an extension that I'd prefer to be lightweight, so I'd rather not use 3rd party libraries.

Is there any way to do this?

Andryc answered 9/2, 2017 at 21:34 Comment(2)
"with function a() not actually returning until I've waited 5 seconds" That's simply not possible, unless Chrome exposes such a functionality to plugins.Annabelannabela
Global await is simply not allowed, presumably for backwards compatibility. You will need to wrap the entire file in an async function.Anthropophagi
S
3

Implicit await is bad, for reasons covered well in this blog. In short, consider why there's no need for locking in JavaScript. It's because we don't worry about being pre-empted willy-nilly.

Also, as mentioned by Daniel in comments, global await is not allowed either, presumably for backwards compatibility.

You can work around this by wrapping your top-level code like this:

let wait = ms => new Promise(r => setTimeout(r, ms));

async function a() {
  console.log("1");
  await wait(5000);
  console.log("2");
}

(async () => {

  // Put your top level code here!

  await a();
  console.log("3");

})().catch(e => setTimeout(() => { throw e; }));

Not perfect, but gets the job done, without turning everything upside down.

Signore answered 10/2, 2017 at 6:4 Comment(4)
"global await is not allowed either" implies that an await expression can be used anywhere else, which is not the case.Marigolde
@zeroflagL If I say "This car is not red either", it doesn't imply all remaining cars are red.Signore
True, but that's completely different. "Red cars are not allowed either" would be more like it. The point is that await is allowed in one situation only: Within async functions. It's not very useful to mention one of many situations where it is not allowed. We don't know if the OP's code is in the global scope.Marigolde
@zeroflagL Like any "I want" question, it's hard to know what the problem really is, but the OP seems aware of what an async function is, so no need for another answer highlighting how that works. The OP is just using it incorrectly from global scope. My statement logic holds, even with "either".Signore

© 2022 - 2024 — McMap. All rights reserved.