gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 23:02:02 24 4
gpt4 key购买 nike

我正在尝试使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com