简体   繁体   中英

Table walk / recursion with Promise

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 .

May use async / await:

(async function(){

  var pageId = 60239;
  while (page_id > 0) {
    pageId = await get_next_id(pageId);
  }

})()

or use indirect recursion:

(function next(pageId){
  if(pageId <= 0) return;
  get_next_id(pageId).then(next);
})(60239);

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
  )
);

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