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
    Posts
  • #245855

    Cloudy Point
    Keymaster

    QuestionQuestion

    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) {
                resolve(r[0].from_visit);
            });
        });
    }
    
    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.

    #245856

    Cloudy Point
    Keymaster

    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) {
          if(e){
            //reject if something goes wrong with error and 
            //  what has been done so far
            reject([e,results]);
            return;
          }
          resolve(r);
        });
      })
      .then(function (r){
        if(r[0].from_visit===0){
          return results;
        }
        //recusively call unless id is 0
        return get_next_id(r[0].from_visit,results.concat(r))
      });
    }
    
    get_next_id(22)
    .then(
      results=>console.log("got results:",results)
      ,([error,resultsSoFar])=>console.error(
        "something went wrong:",error,
        "results before the error:",resultsSoFar
      )
    );
    

    Source: https://stackoverflow.com/questions/48026558/table-walk-recursion-with-promise
    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.