【发布时间】:2018-06-13 05:31:46
【问题描述】:
我正在使用 Promise 在 React 中调度异步操作。我只想更改对象的属性。该功能有效。如果我将代码包装在一个承诺中并且在执行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(即操作)。但是,如果我在承诺的括号之后执行then 并记录它会显示日志。
我不是 JS 专家。我真的很努力,这真的让我着迷。有什么想法吗?
在此先感谢
【问题讨论】:
-
因为我不能
edit我自己的问题是 privilege 只有少数我想声明日志“设置值”出现在控制台中,如果我在返回之前放了一个日志,我得到了显示的日志。未执行的是then部分。非常感谢提前 -
除了
else之外,您不是resolve的承诺,因此then不会被执行。您也可以编辑自己的问题(总是)。 -
我建议避免使用 Promise 构造函数完全 并使用 Promisified API(API 已经返回 Promise)或
Promise.resolve创建一个固定值的 Promise。 -
谢谢@BenjaminGruenbaum 这确实有效。您可以将其写成答案,以便我将其标记为答案并投票吗?非常感谢。经验教训
-
我赞成 Benjamin 使用 promise 库的建议,因为我认为它可以帮助您澄清这个逻辑。您当前的实现在我看来很奇怪。让一个函数“setValue”有条件地返回一个承诺是令人困惑的。
标签: reactjs promise react-redux dispatch