Reputation: 734
I am using a promise to dispatch an asynchronous action in react. I just want to change the properties of an object. The function works. If I wrap the code in a promise and after doing Promise().then
works but if I do myFunction(params).then()
the then is not called
here is my function. (It is recursive):
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))
})
}
}
the console shows "we are indeed here" but not "Poco is here" and changePoco (that is the action) is not called. However if I do a then
right after the brackets of the promises and log it shows the log.
I am not an expert in JS. I am trying really hard and this really got me. Any ideas?
Many thanks in advance
Upvotes: 0
Views: 50
Reputation: 276286
You are not resolve
ing the promise except in the else
so the then doesn't get executed.
Upvotes: 1