0

I have a function,

  asdf() {
    var a = fooController.getOrCreateFooByBar(param);
    console.log("tryna do thing");
    console.log(a); //undefined
    if (!a.property) {
      //blah
    }

that dies. getOrCreateFooByBar does a

  Model.find({phoneNumber : number}).exec()
  .then(function(users) {})

and finds or creates the model, returning it at the end:

.then(function(foo) { return foo}

How can I use the result of this in asdf()? I feel like this is a fairly easy question but I am getting stuck. If I try to do a.exec() or a.then() I get 'a cannot read property of undefined' error.

Austin Gayler
  • 4,038
  • 8
  • 37
  • 60

1 Answers1

2

The main idea about Promises (as opposed to passed callbacks) is that they are actual objects you can pass around and return.

fooController.getOrCreateFooByBar would need to return the Promise it gets from Model.find() (after all of the processing done on it). Then, you'll be able to access it in a in your asdf function.

In turn, asdf() should also return a Promise, which would make asdf() thenable as well. As long as you keep returning Promises from asynchronous functions, you can keep chaining them.

// mock, you should use the real one
const Model = { find() { return Promise.resolve('foo'); } }; 

function badExample() {
  Model.find().then(value => doStuff(value));
}

function goodExample() {
  return Model.find().then(value => doStuff(value));
}

function asdf() {
  var a = badExample();
  var b = goodExample();

  // a.then(whatever); // error, a is undefined because badExample doesn't return anything

  return b.then(whatever); // works, and asdf can be chained because it returns a promise!
}

asdf().then(valueAfterWhatever => doStuff(valueAfterWhatever));
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308