NodeJS [SOLVED]: Table walk / recursion with Promise

NodeJS [SOLVED]: Table walk / recursion with Promise

Home Forums Scripting NodeJS Tutorials NodeJS [SOLVED]: Table walk / recursion with Promise

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #245855

    Cloudy Point


    I would like to walk a database table using Promises to get the data from each step synchronously. I think my code should look something like:

    function get_next_id(the_id) {
        return new Promise(function(resolve) {
            connection.query(get_parent_query, [ the_id ], function (e, r, f) {
    var page_id = 60239;
    while (page_id > 0) {
        get_next_id(page_id).then((i) => page_id = i);

    The problem with this code is that the loop iterates immediately without waiting for the then() to complete.

    In this answer the poster suggests either using Promise.race() or abandoning Promise altogether in favor of async.


    Cloudy Point

    Accepted AnswerAnswer

    I don’t understand why you want to get a bunch of id’s but not do anything with the results. Your original function was almost there but you should reject with the error and the results so far if something goes wrong.

    And resolve with all the results if everything goes right:

    function get_next_id(the_id,results=[]) {
      return new Promise(function (resolve,reject) {
        connection.query(get_parent_query, [the_id], function (e, r, f) {
            //reject if something goes wrong with error and 
            //  what has been done so far
      .then(function (r){
          return results;
        //recusively call unless id is 0
        return get_next_id(r[0].from_visit,results.concat(r))
      results=>console.log("got results:",results)
        "something went wrong:",error,
        "results before the error:",resultsSoFar

    Author: HMR
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.