Node.js超出最大调用堆栈

时间:2016-07-29 23:02:04

标签: javascript node.js recursion node-mysql node-request

我有same question as earlier,但无法将答案与我的代码联系起来。这是我的错误:RangeError: Maximum call stack size exceeded

我的代码的高度简化的伪版本是:

function make_request(url, other_params){ 

  request(url, function(response){

    if(something) var some_var = 'some value';
    else var some_var = '';

    //do something with response to generate, some_var, and insert into DB

    var my_arr = [some_var];

    connection.query('INSERT my_table SET name = ?', my_arr, function(err, rows, fields) {
         if(my_arr==''){
               // generate new url to make new request
               make_request(url, other_params);
         }
    });

  });
}

connection.query('SELECT * from my_table', function(err, rows, fields){

  var len =rows.length;

  for(var i = 0; i < len; i++){

    var url = rows[i].url;

    make_request(url, other_params);

  }     
});

我尝试将make_requestsetImmediate中的内部setTimeout包装在其他一些黑客中,但似乎没有任何东西阻止调用堆栈错误。我可以添加任何可以使这项工作的库。任何想法都将不胜感激。

2 个答案:

答案 0 :(得分:1)

如果我正确读取代码,则阻止

     if(my_arr==''){
           // generate new url to make new request
           function make_request(url, other_params);
     }

make_request 重新定义为空函数。你不想在这一点打电话吗?我认为null重定义会让你进行无法终止的间接递归。

答案 1 :(得分:1)

尝试更改代码

function make_request(url, other_params, callback){ // all async function mast have callback 
    // Hmmm...
    // request(url, function(response){ 
    request(url, function(err, response){  // according by doc - https://github.com/request/request
        // Use short notation
        var some_var = (smth) ? 'some-value' : '';

        // do-smth. Mayby problem is here?

        var my_arr = [some_var];
        connection.query('INSERT my_table SET name = ?', my_arr, function(err, rows, fields) {
            // Always check error
            if(err)
                return callback(err);

            // I don't understand what is it. If some_var == '' then my_arr == [], not ''
            // In any case this check must do on upper level
            /*
            if(my_arr=='')
                make_request(url, other_params);
            */
            callback(null, rows); // return data    
        });
    });
}


var async = require('async');

connection.query('SELECT url from my_table', function(err, rows, fields){ // if you need one field then don't request all
    // I repeat: Always check error. SQL can be correct, but db is busy.
    if (err)
        return console.log(err.message); 

    async.mapSeries(rows, make_request, function(err, results) {
        if (err)
            return console.log(err);

        // do smth with results 
        console.log(results);   
    });      
});

P.S。 heinob 在上一篇你的问题做出了非常好的答案。