1

I have a solution where i have 2 loops inside each other it looks like this:

function myFunc(types, pages, callback) {
    var pageResults = [];
    for (var i = 0; i < types.length; i++) {
        var type = types[i];
        for (var j = 1; j < pages; j++) {
            getBikes(type, j, function(err, results, settings){
                if(err) throw err;
                var obj = {
                    results: results,
                    settings: settings
                };
                pageResults.push(obj);
            });
        };
    };
    return callback(pageResults);
});

var types = ["string1", "string2", "string3", "string4"];
var pages = 15;
myFunc(types, pages, function(pageResults){
    console.log("done");
});

But this ends right away it returns after 1 loop in the types loop, and if i log the obj that i return from the inner function without returning a callback it will run all the way through.

Yes getBikes is a async call similar to ajax, but in nodejs, with a module called request.js

Simon Dragsbæk
  • 2,367
  • 3
  • 30
  • 53
  • `getBikes()` is a `ajax` function? – Ja9ad335h May 07 '15 at 19:32
  • is `getBikes` asynchronous? – Igor May 07 '15 at 19:32
  • [How can I wait for set of asynchronous callback functions?](http://stackoverflow.com/questions/10004112/how-can-i-wait-for-set-of-asynchronous-callback-functions) / [waiting for a number of asynchronous callbacks to return?](http://stackoverflow.com/questions/10291139/javascript-waiting-for-a-number-of-asynchronous-callbacks-to-return) – Jonathan Lonowski May 07 '15 at 19:36
  • Its a request(function) which is a nodejs module that can request stuff, like ajax for nodejs – Simon Dragsbæk May 07 '15 at 19:51

1 Answers1

-1

you can not return the callback value but you can call the callback function like below

function myFunc(types, pages, callback) {
    var pageResults = [];
    for (var i = 0; i < types.length; i++) {
        var type = types[i];
        for (var j = 1; j < pages; j++) {
            getBikes(type, j, function(err, results, settings){
                if(err) throw err;
                var obj = {
                    results: results,
                    settings: settings
                };
                pageResults.push(obj);
                if((i === types.length-1) && (j === pages -1)){
                   callback(pageResults);
                }
            });
        };
    };
});
Sunand
  • 703
  • 4
  • 9