0

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.

In stormjs (developing https://github.com/guileen/stormjs/issues/1), it write as

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.

2
  • Won't the above code be automatically synchronous irrespective of whether you're calling async functions and callbacks or not? Commented May 20, 2011 at 8:37
  • @Denis he's using an async shorthand _ is some kind of magic flow control thing. Commented May 20, 2011 at 8:38

1 Answer 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.

(function recurse(i, err, url) {
    if (!err) arr.push(url);

    if (i < 100) getNextUrl(url, recurse.bind(null, ++i));
}(0, "trick it", url);
Sign up to request clarification or add additional context in comments.

2 Comments

Can I drop the 3rd arguments urlarr
@guilin yes if you want to make it global.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.