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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With