javascript - async.whilst 中的 callback 和 err 是做什么用的?

标签 javascript node.js while-loop async.js

我正在尝试使用 async.whilst 重新生成一个介于 0 和数组长度之间的随机数,直到该索引上的元素长度大于指定长度。我想为此使用 async.whilst,但语法对我来说并不完全清楚。我考虑过执行以下操作:

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]);
        }
    }

但是,这是行不通的。我想这是因为我没有在任何地方将 cb 用于第二个功能,但我不完全知道我应该如何使用它。更改索引后我只调用 cb() 吗?变量err到底包含什么?

最佳答案

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

是的,没错。 async.js 希望您在完成后回调,如果您不这样做,它将不会继续进行下一次迭代。

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

你根本不应该使用它,因为你没有做任何异步的事情。使用标准的 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

关于javascript - async.whilst 中的 callback 和 err 是做什么用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29969647/

相关文章:

javascript - 如何使用 JSON 类型索引从 JSON 变量获取数据

node.js - 在没有 sudo 的 EC2 : node. js 上

javascript - 如何利用 while 循环来制作动画并显示总计

javascript - 为什么这个延迟的 WHILE 循环会导致大量内存泄漏?

javascript - 带有动态变量的正则表达式不起作用

javascript - 自定义模块 Hubspot 内的 RAW HTML 模块

javascript - $(window).resize 是做什么的?移动版

node.js - 是否可以打包一个 'real' mongodb 库以仅在 meteor 0.6 中用于 *server* 端

node.js - 在passport.js中使用req.params作为passport.authenticate()的输入(使用Express 4.0)

sql-server - SQL Server 使用 WHILE 循环添加计算列