0

I'm using Node.js and q library.

I have a code that looks like this:

checkIfThingExists(function(idForAThing){
  if(idForAThing){
    updateThingData(idForAThing);
  } else {
    createThing(function(idForAThing){
      updateThingData(idForAThing);
    });
  }
})

As you can see I need to call updateThingData(); twice.

Is there a way I can use promises to call updateThingData() just once, for example something like this? Of course this does not work and idForAThing is always undefined when the if statement runs:

checkIfThingExists(function(idForAThing){

  if(!idForAThing){
    createThing().then(function(newIdForAThing){
      idForAThing = newIdForAThing
    })
  }

  updateThingData(idForAThing);
})
Skullers
  • 75
  • 7
  • 1
    No, it's not possible to get the value before the `then` callback, that's the whole point of promises. However, you [can use a promise conditionally and carry on asynchronously](https://stackoverflow.com/a/39621747/1048572). – Bergi Sep 04 '17 at 13:49

2 Answers2

0

Actually, what is happening is the .then method is a callback. It doesn't get called until after updateThingData is called.

You could instead create a promise chain that will resolve after it has the ID. Then chain the next .then callback to call updateThingData. Here is an example of that:

checkIfThingExists(function(idForAThing){
  return Q.resolve() // or Promise.resolve if you were using the browser implementation
    .then(function() {
      if(!idForAThing) return createThing()
      return idForAThing
    })
    .then(updateThingData)
})
Goblinlord
  • 3,290
  • 1
  • 20
  • 24
0

You have to return in any case a promise. So:

checkIfThingExists(function(idForAThing){
  var promise

  if(!idForAThing)
    promise = createThing()
  else
    promise = Promise.resolve(idForAThing)

  promise.then(function(id){
    updateThingData(id)})
  }
Nderim
  • 9
  • 1
  • 3