承诺不在外面执行,但它在函数内部

时间:2018-06-12 20:42:22

标签: reactjs promise react-redux dispatch

我正在使用promise来响应中调度异步操作。我只想更改对象的属性。该功能有效。如果我将代码包装在一个承诺中并且在Promise().then工作之后,但是如果我myFunction(params).then() then is not called这里是我的函数。 (这是递归的):

export function setValue(propertyPath, value, obj) {
  console.log("setting the value")
  return new Promise((resolve, reject) => {
      // this is a super simple parsing, you will want to make this more complex to handle correctly any path
      // it will split by the dots at first and then simply pass along the array (on next iterations)
      let properties = Array.isArray(propertyPath) ? propertyPath : propertyPath.split(".")

      // Not yet at the last property so keep digging
      if (properties.length > 1) {
        // The property doesn't exists OR is not an object (and so we overwrite it) so we create it
        if (!obj.hasOwnProperty(properties[0]) || typeof obj[properties[0]] !== "object") obj[properties[0]] = {}
        // We iterate.
        return setValue(properties.slice(1), value, obj[properties[0]])
        // This is the last property - the one where to set the value
      } else {
        // We set the value to the last property
        obj[properties[0]] = value
        console.log("modified object")
        console.log(obj)
        return resolve(obj)
      }
    }
  )
}

export function performPocoChange(propertyPath, value, obj) {
  console.log("we are indeed here")
  return (dispatch) => {
    setValue(propertyPath, value, obj).then((poco) => {
      console.log("poco is here")
      console.log(poco)
      dispatch(changePoco(poco))
    })
  }
}

控制台显示“我们确实在这里”但不是“Poco在这里”并且没有调用changePoco(即动作)。但是,如果我在promises的括号后面执行then并记录日志。

我不是JS的专家。我真的很努力,这真的让我受益匪浅。有什么想法吗?

非常感谢提前

1 个答案:

答案 0 :(得分:1)

除了resolve之外,你不是else承诺,所以当时并没有执行。

相关问题