Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the callback and err in async.whilst used for?

I'm trying to use async.whilst to regenerate a random number between 0 and the length of an array, until the length of the element on this index is larger than a specified length. I wanted to use async.whilst for this, but the syntax is not completely clear to me. I thought about doing the following:

var selectParagraph = function(paragraphs, callback){
    var index = Math.floor(Math.random() * paragraphs.length
    async.whilst(
        function(){ 
            return paragraphs[index].length < minParagraphLength; 
        },
        function(cb) {
            index = Math.floor(Math.random() * paragraphs.length);
        },
        function(err) {
            console.log(paragraphs[index]);
            callback(err, paragraphs[index]);
        }
    }

However, this doesn't work. I suppose it is because I didn't use the cb for the second function anywhere, but I don't exactly know how I should use it. Do I just call cb() after changing the index? What exactly does the variable err contain?

like image 584
Eva Avatar asked Mar 16 '23 05:03

Eva


1 Answers

I suppose it is because I didn't use the callback for the second function anywhere

Yes, exactly. async.js expects you to call back when you're done, and when you don't it will not continue with the next iteration.

but I don't exactly know how I should use it

You shouldn't use it at all, since you are doing nothing asynchronous. Use a standard do while loop:

do {
    var index = Math.floor(Math.random() * paragraphs.length); 
} while (paragraphs[index].length < minParagraphLength)
console.log(paragraphs[index]);

callback(null, paragraphs[index]); // not sure where you're getting `callback` from
like image 147
Bergi Avatar answered Apr 01 '23 02:04

Bergi