是否可以在.then()范围之外获取.resolve()返回的值?

时间:2017-09-04 13:09:18

标签: javascript node.js q

我使用的是Node.js和q库。

我的代码如下:

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

如您所见,我需要调用updateThingData();两次。

有没有办法可以使用promises只调用updateThingData()一次,例如这样的事情?当然,当if语句运行时,这不起作用,idForAThing总是undefined

checkIfThingExists(function(idForAThing){

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

  updateThingData(idForAThing);
})

2 个答案:

答案 0 :(得分:0)

实际上,正在发生的事情是.then方法是一个回调。在调用updateThingData之前,它不会被调用。

您可以创建一个在拥有ID后将解析的承诺链。然后链接下一个.then回调以调用updateThingData。这是一个例子:



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




答案 1 :(得分:0)

你必须在任何情况下都返回一个承诺。 所以:

checkIfThingExists(function(idForAThing){
  var promise

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

  promise.then(function(id){
    updateThingData(id)})
  }