What is callback and error in async.whilst?

I am trying to use async.whilst to restore a random number between 0 and the length of an array while the length of the element in this index is greater than the specified length. I wanted to use async.whilst for this, but the syntax is not entirely clear to me. I thought of 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 does not work. I suppose this is because I did not use cb for the second function anywhere, but I do not know exactly how I should use it. Am I just calling cb () after changing the index? What exactly does the err variable contain?

+4
source share
2 answers

Bergi , whilst. , whilst.

whilst - , . whilst , "" , . - whilst, , whilst .

, . ( , , .)

var i = 0;
async.whilst(
    function(){ return i < 5; },

    function(cb) {
        setTimeout(function() {
            console.log(i++);
            cb();
        }, 1000);
    },

    function(err) { console.err("we encountered an error", err); }
);

setTimeout, whilst , setTimeout cb(). whilst , , setTimeout , , . , cb().

cb() , whilst , , . whilst , , cb().

cb() , . ( , ), cb (, cb(new Error("could not reach the server"));), whilst .

+3

, , -

, . async.js , , , , .

,

, . do while:

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
+4

All Articles