1

Say that you have a function f that does some asynchronous operations by calling a long-running function g and waits for its result before doing more work.

Back in the day when we didn't have async/await, and were forced to use callbacks, I used to do something like this to know if f had finished running. By this, I mean that f and all the asynchronous things it was doing had completed:

let running = false;
function f() {
    running = true;
    g(function() {
        running = false;
    });
};

Now we have ES6, and I can still do something similar using async/await:

let running = false;
async function f() {
    running = true;
    await g();
    running = false;
};

However, I'm wondering if there is a more elegant way of doing the same thing, without having to write a wrapper or aynthing like that, because obviously the JavaScript engine must know whether f is finished running or not (i.e. it must know if it's paused its executinon with the await keyword, and can be resumed).

Is there any way for my code to know this too?

I know there are modules and libraries that let you do that, and yes I could write a wrapper function, but that's not what I'm after.

Gio
  • 841
  • 1
  • 5
  • 11
  • Just use the Promise API? `g().then(() => markFinished())` – VLAZ Feb 13 '20 at 12:32
  • JS is not actually pausing the execution with the `await` word. It is just a syntactic sugar, it creates a callback to your function basically. Just so you know. Sadly, your code is fine, it is your responsibility to know the state of your function. – sshanzel Feb 13 '20 at 12:42
  • 1
    You can check this question, it is similar to what you asked https://stackoverflow.com/questions/55002028/javascript-how-to-check-if-async-operation-is-still-pending-in-progress – Dawood Valeed Feb 14 '20 at 11:44

0 Answers0