简体   繁体   中英

writing a while loop in node.js

In c# I would do this -

double progress = 0;
while (progress < 100) 
{ 
    var result = await PerformAsync(); 
    progress = result.Progress; 
    await Task.Delay(); 
} 

A nice simple 7 lines of code. What's the equivalent in node.js ? Basically need a while loop that checks a condition, and until that condition is met, sleeps and then executes some async operation.

There's a fundamental paradigm shift when you think in the Node.js way.

As had been written and said about in node " Everything runs in parallel except your code" . JS is single threaded and hence if you make that thread sleep , everything blocks.

But if you model your problem in a natural way , it would be to design an async operation that would take its time to run and when its finished let it inform you of the same. Rather than you waiting for it to finish.

This you would design your async (performAsync) operation to emit events and then provide a callback to be performed when that event occurs.

So it's even more compact and natural. Your code might look like

performAsync().on('result',function cb () {// do what pleases you});

In general, when you have a question of the form

"There's a thing I can do in language A ; how do I do it in language B ?"

check hyperpolyglot . It's a page that provides summaries of certain terms and concepts across various language classes.

The scripting page shows you, among other things, how to use a while loop in JS, Python, Ruby and PHP.

Node.js, as you guess, its a javascript file. So you can use javascript codes. But there is a few differ about what should you use. In exmaple; with Node.js you can want to use sync while;

var page = 2;
var last_page = 100;

(function loop() {
    if (page <= last_page) {
        request("/data?page=" + page, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                store_data(body)
            }
            page++;
            loop();
        });
    }
}());

On the example we call loop() function in loop(), so not on technically but on practically we are using loop.

Async example : async for loop in node.js

看看https://github.com/caolan/async ,它有很多用于此类同步任务的方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM