1

I'm just curious about doing asynchronous job with javascript or typescript.
I made some program with C# and following is source that I wrote.

static void Main(string[] args)
{
    var t1= Task.Run(() => { myFunc(0, ConsoleColor.Green); });
    var t2 = Task.Run(() => { myFunc(50000, ConsoleColor.Red); });

    t1.Wait();
    t2.Wait();
}

static void myFunc(int number, ConsoleColor color)
{

    for (int i = 0; i < 1e4; i++)
    {
        Console.ForegroundColor = color;
        Console.WriteLine(number + i);
    }
}

below is capture image of result.
enter image description here

I can imagine that why console does write above result.

and following source is written in typescript. I tried to simulate same result, but failed.

let i: number;
let j: string;
let k: number;
let mx: number =1e4;

function myFunc(offset: number, color: string) {

    return new Promise(() => {

        for (i = 0; i < mx; i++) {
            console.log(color, i + offset);
        }
    });

};

async function myFunc2() {
    const aa = myFunc(0, "\x1b[32m");
    const bb = myFunc(50000, "\x1b[35m");
    await aa;
    await bb;

}

myFunc2();

below image is typescript one. enter image description here

can I get any advice for making same result with C# result in `java(type)script? I tried many times to implement, but many time I failed.
thank you for read.

1
  • 2
    As far as I know, JavaScript is single-threaded. What you do in C# with "Task.Run" is to execute the code on a threadpool thread, which you do not have in JavaScript (nor TypeScript). You may get some results when looking for "multithreaded javascript" that may suggest work-arounds. Commented Oct 15, 2019 at 7:37

1 Answer 1

3

JavaScript has only one thread in the same context, but the web browser APIs do not. We also have the possibility of simulating parallelism by using the setTimeout function or, with some limitations, by using the real parallelism provided by WebWorkers.

https://www.w3schools.com/jsref/met_win_settimeout.asp

https://www.w3schools.com/html/html5_webworkers.asp

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.