Home > other >  Is there a Task.Run equivalent in JavaScript?
Is there a Task.Run equivalent in JavaScript?

Time:07-06

In C# there is the Task.Run(() => {}) method which makes it easy to run code asynchronously. Is there an equivalent method in JavaScript?

So far, the closes I've gotten is nested usage of setTimeout like this:

setTimeout(async function logStatus() {
    const result = await someNetworkCall();
    console.log(result);
    setTimeout(() => {
      logStatus();
    }, 1000);
  }, 1000);

The above code simply calls a network service once a second and logs the result to the console. However, I'm worried about getting an eventual stackoverflow exception due to the recursive way of letting the logStatus method call logStatus from within itself.

Is there a better way?

CodePudding user response:

While I'm by no stretch of the imagination a JS expert (or even proficient in JS), you should he able to use immediately-invoked Function Expressions and the fact that promises are always immediately executed to do achieve this, something like

// we want/ need a promise based sleep function
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// now our actual continuously running function
// this is a IIFE: https://flaviocopes.com/javascript-iife/
(async () => {
    while (true) {
        const result = await someNetworkCall();
        console.log(result);
        await sleep(1000);
    }
})()

You'll probably want to implement something so you can cancel that while (true) loop, but I'll leave that up to you

The equivalent to Task.Run(async () => ... ) would be (async () => ... )() as far as I can tell, and the equivalent to a C# Task is a Promise

I created a jsfiddle you can run in your browser demonstrating the core concept here (don't worry, I replaced the while true loop with a for loop that goes to 10 so it actually stops running)

  • Related