have a initUrl, its an article which contains next blog, and defind function getNextUrl(url, callback(err, nextUrl))
, want to get the next 100th url.
有一个initUrl,它的文章包含下一个博客,并且定义函数getNextUrl(url,callback(err,nextUrl)),想得到下一个第100个url。
In stormjs (developing https://github.com/guileen/stormjs/issues/1), it write as
在stormjs(开发https://github.com/guileen/stormjs/issues/1)中,它写为
var url = initUrl;
for(var i=0; i<100; i++){
url = getNextUrl(url, _);
}
console.log(url);
but what the best output should be, I want to know how noders write this code without 3rd module.
但是最好的输出应该是什么,我想知道noders如何在没有3rd模块的情况下编写这个代码。
1 个解决方案
#1
3
arr = [];
(function recurse(url, i) {
getNextUrl(url, function(err, nextUrl) {
if (!err) {
arr.push(nextUrl);
if (i < 100) recurse(nextUrl, i++);
}
});
}("", 0);
I call this pattern boot strapped recursion.
我把这种模式称为引导绑定递归。
If you prefer it to be more concise rather then efficient you can use some .bind
magic.
如果你更喜欢它更简洁而又更有效率,你可以使用一些.bind魔法。
(function recurse(i, err, url) {
if (!err) arr.push(url);
if (i < 100) getNextUrl(url, recurse.bind(null, ++i));
}(0, "trick it", url);
#1
3
arr = [];
(function recurse(url, i) {
getNextUrl(url, function(err, nextUrl) {
if (!err) {
arr.push(nextUrl);
if (i < 100) recurse(nextUrl, i++);
}
});
}("", 0);
I call this pattern boot strapped recursion.
我把这种模式称为引导绑定递归。
If you prefer it to be more concise rather then efficient you can use some .bind
magic.
如果你更喜欢它更简洁而又更有效率,你可以使用一些.bind魔法。
(function recurse(i, err, url) {
if (!err) arr.push(url);
if (i < 100) getNextUrl(url, recurse.bind(null, ++i));
}(0, "trick it", url);