0

I have a method that returns an promise of an object (by id) from a database asynchronously.

function getObj(id){}....returns promise of object

It may or may not have a reference to another object by storing its id.

object.nextObjId

I need to traverse the reference chain until I find the terminal object using this method. Obviously I must wait for the promise to resolve before I can check for the next reference.

In synchronous code it would look like this:

function getTerminalObj(id)
{
    var obj = getObj(id);
    while(obj.nextRef)
    {
       obj = getObj(obj.nextObjId);
    }

    return obj;
}

How do I do this when getObj(id) instead returns a promise of an object?

Cœur
  • 37,241
  • 25
  • 195
  • 267
DSE
  • 29
  • 1
  • 1
  • 2
  • did you check this [link](http://stackoverflow.com/questions/29925948/building-a-promise-chain-recursively-in-javascript-memory-considerations)? – Carlos Arauz Dec 02 '16 at 04:51

1 Answers1

1

Correct me if I am wrong. I think you are asking "how to resolve a promise in a synchronized fashion". In a context of JS/NodeJS, there are a few options:

ES6: Co.js / Generators

ES7: await/async Async Functions

Both approaches need you to either:

  • Have a relatively new version of JS implementation.
  • Use babel to transform ES6/ES7 code to old ES5 code.

However, I would say you don't have to do this in a synchronized fashion. The following code may help:

function chain(obj) {
  if (obj.nextRef) {
    return getObj(obj.nextObjId).then(chain);
  }
  return Promise.resolve(obj);
}

getObj(id).then(chain).then(function(terminalObj) {
  // There is the terminal object.
  console.log(terminalObj);
});
Ming
  • 4,110
  • 1
  • 29
  • 33
  • unfortunately, I cannot use anything above ES5 at this point. – DSE Dec 02 '16 at 06:15
  • "When using node 0.10.x and lower or browsers without generator support, you must use gnode and/or regenerator." from https://github.com/tj/co#platform-compatibility – Ming Dec 02 '16 at 06:33