简体   繁体   中英

JavaScript, Node.js: given function undefined in async.each() callback

I have a node.js server, which, upon request, sends a svg (which takes a rather longer time to build) to the client, and to stop it from sending an incomplete svg to the client, I have used async.each() for the loop which builds the svg.

To call the write function etc. I use a callback function, which I pass on to the function building the svg, to be called as soon as the async.each() has finished.

However the async.each, when called upon, says the callback function I gave the svg builing function does not exist. Why is that, and how can I call it?

 function sendSVG(res){ var str = "somePredefinedStuff"; buildSVG(str,function(){ str += "someEndStuff"; res.write(str); res.end(); }); } function buildSVG(str,callback){ var array = [1,2,3]; async.each(array, function(a){ str += "moreStuff"; buildSVG(str); str += "moreEndStuff"; },function(err){ console.log(typeof callback); //always returns undefined. Should actually return function once? if(callback) callback(); }); } 

Edit: the problem turned out to be in another part of the code (a case in which the callback was never called). The string is still only sent in it's original form, but there should be a workaround for that.

You aren't passing a callback in your nested buildSVG call. Presumably what you want is:

async.each(array, function(a, cb) {
  str += “moreStuff”;
  buildSVG(str, function() {
    str += “moreEndStuff”;
    cb(); // call next async func
  });
}, callback);

I am assuming you are using the nodejs async library, if that is the case you need to call the next function to continue the iteration. Take a look at the code below

function sendSVG(res){

  var data = {str: "somePredefinedStuff"};

  buildSVG(data, function(){
    data.str += "someEndStuff";
    res.write(data.str);
    res.end();
  });

}

function buildSVG(data, callback){

  var array = [1,2,3];

  async.each(array, function(a, next){
    data.str += "moreStuff";
    buildSVG(data, function () {
        data.str += "moreEndStuff";
        setImmediate(next);
    });        
  },function(err){

    console.log(typeof callback); //always returns undefined. Should actually return function once?
    if(callback)
      callback();

  });
}

Keep in mind this code is causing an infinite loop because of the recursion so you need to add a base case that will break that recursion. Or change it so it doesn't use recursion at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM