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?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Drew
  • 670
  • 8
  • 26
  • 1
    *"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. – Felix Kling Feb 09 '17 at 21:37
  • Global await is simply not allowed, presumably for backwards compatibility. You will need to wrap the entire file in an async function. – Daniel Herr Feb 09 '17 at 23:14

1 Answers1

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.

jib
  • 40,579
  • 17
  • 100
  • 158
  • _"global await is not allowed either"_ implies that an await expression can be used anywhere else, which is not the case. – a better oliver Feb 10 '17 at 14:12
  • 1
    @zeroflagL If I say "This car is not red either", it doesn't imply all remaining cars are red. – jib Feb 11 '17 at 14:37
  • 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. – a better oliver Feb 13 '17 at 08:29
  • 1
    @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". – jib Feb 13 '17 at 14:42