Asynchronous Calls and Recursion with Node.js

后端 未结 6 720
[愿得一人]
[愿得一人] 2021-02-09 10:34

I\'m looking to execute a callback upon the full completion of a recursive function that can go on for an undetermined amount of time. I\'m struggling with async issues and was

6条回答
  •  Happy的楠姐
    2021-02-09 11:29

    If your recursive function is synchronous, just call the callback on the next line:

    var start = function(callback) {
      request.get({
        url: 'aaa.com'
      }, function (error, response, body) {
        var startingPlace = JSON.parse(body).id;
        recurse(startingPlace, otherFunc);
        // Call output function AFTER recursion has completed
        callback();
      });
    };
    

    Else you need to keep a reference to the callback in your recursive function.

    Pass the callback as an argument to the function and call it whenever it is finished.

    var start = function(callback) {
      request.get({
        url: 'aaa.com'
      }, function (error, response, body) {
        var startingPlace = JSON.parse(body).id;
        recurse(startingPlace, otherFunc, callback);
      });
    };
    

提交回复
热议问题