Creating a promise chain for a deeply nested object
I have a deep object:
{
"something": "Homepage",
"else": [
"[replaceme]",
"[replaceme]"
],
"aside": "[replaceme]",
"test": {
"test": {
"testing": [
"[replaceme]",
"[replaceme]",
"variable",
{
"testing": {
"testing": {
"something": "[replaceme]",
"testing": {
"testing": [
"[replaceme]",
"[replaceme]"
]
}
}
}
}
]
}
}
}
Now I need to replace every occurrence [replaceme]
with what comes out of the async function. It is different every time.
I thought I was decreasing each level of the object and returning the promise chain.
This is what I got so far:
const IterateObject = ( object ) => {
return new Promise( ( resolve, reject ) => {
Object.keys( object ).reduce( ( sequence, current ) => {
const key = current;
return sequence.then( () => {
return new Promise( ( resolve, reject ) => {
if( typeof object[ key ] === 'object' ) {
IterateObject( object[ key ] )
.then( result => {
newObject[ key ] = result;
});
// ^----- How do I add the next level when it returns a promise?
}
else {
resolve( newObject[ key ] )
}
});
});
}, Promise.resolve())
.catch( error => reject( error ) )
.then( () => {
console.log('done');
resolve();
});
});
}
Question
What is the best way to solve this problem? Maybe a promise chain isn't the best tool?
source to share
Don't try to do this in one function. This can lead to the general anti-pattern being known as The Collection Kerfuffle Splitting this task into separate chunks: deep intersection object, asynchronous setter, etc. Collect all pending promises by traversing your object and wait for them all usingPromise.all
// traverse object obj deep using fn iterator
const traverse = (obj, fn) => {
const process = (acc, value, key, object) => {
const result =
Array.isArray(value)
? value.map((item, index) => process(acc, item, index, value))
: (
typeof value === 'object'
? Object.keys(value).map(key => process(acc, value[key], key, value))
: [fn(value, key, object)]
)
return acc.concat(...result)
}
return process([], obj)
}
// fake async op
const getAsync = value => new Promise(resolve => setTimeout(resolve, Math.random()*1000, value))
// useful async setter
const setAsync = (target, prop, pendingValue) => pendingValue.then(val => target[prop] = val)
// traverse object obj deep using fn iterator
const traverse = (obj, fn) => {
const process = (acc, value, key, object) => {
const result =
Array.isArray(value)
? value.map((item, index) => process(acc, item, index, value))
: (
typeof value === 'object'
? Object.keys(value).map(key => process(acc, value[key], key, value))
: [fn(value, key, object)]
)
return acc.concat(...result)
}
return process([], obj)
}
// set async value
const replace = (value, prop, target) => {
if( value === '[replaceme]') {
return setAsync(target, prop, getAsync(`${prop} - ${Date.now()}`))
}
return value
}
const tmpl = {
"something": "Homepage",
"else": [
"[replaceme]",
"[replaceme]"
],
"aside": "[replaceme]",
"test": {
"test": {
"testing": [
"[replaceme]",
"[replaceme]",
"variable",
{
"testing": {
"testing": {
"something": "[replaceme]",
"testing": {
"testing": [
"[replaceme]",
"[replaceme]"
]
}
}
}
}
]
}
}
}
Promise.all(
traverse(tmpl, replace)
)
.then(() => console.log(tmpl))
.catch(e => console.error(e))
Or you can take a look at async/await
which will allow you to write more "synchronous" code. But this implementation results in sequential execution.
// using async/await
const fillTemplate = async (tmpl, prop, object) => {
if(Array.isArray(tmpl)) {
await Promise.all(tmpl.map((item, index) => fillTemplate(item, index, tmpl)))
}
else if(typeof tmpl === 'object') {
await Promise.all(Object.keys(tmpl).map(key => fillTemplate(tmpl[key], key, tmpl)))
}
else {
await replace(tmpl, prop, object)
}
}
const tmpl = {
"something": "Homepage",
"else": [
"[replaceme]",
"[replaceme]"
],
"aside": "[replaceme]",
"test": {
"test": {
"testing": [
"[replaceme]",
"[replaceme]",
"variable",
{
"testing": {
"testing": {
"something": "[replaceme]",
"testing": {
"testing": [
"[replaceme]",
"[replaceme]"
]
}
}
}
}
]
}
}
}
// fake async op
const getAsync = value => new Promise(resolve => setTimeout(resolve, Math.random()*1000, value))
// useful async setter
const setAsync = (target, prop, pendingValue) => pendingValue.then(val => target[prop] = val)
// set async value
const replace = (value, prop, target) => {
if( value === '[replaceme]') {
return setAsync(target, prop, getAsync(`${prop} - ${Date.now()}`))
}
return value
}
// using async/await
const fillTemplate = async (tmpl, prop, object) => {
if(Array.isArray(tmpl)) {
await Promise.all(tmpl.map((item, index) => fillTemplate(item, index, tmpl)))
}
else if(typeof tmpl === 'object') {
await Promise.all(Object.keys(tmpl).map(key => fillTemplate(tmpl[key], key, tmpl)))
}
else {
await replace(tmpl, prop, object)
}
}
Promise
.resolve(fillTemplate(tmpl))
.then(() => console.log(tmpl))
.catch(e => console.error(e))
source to share
I think this is similar to what you are trying to do.
var object =
{
"something": "Homepage",
"else": [
"[replaceme]",
"[replaceme]"
],
"aside": "[replaceme]",
"test": {
"test": {
"testing": [
"[replaceme]",
"[replaceme]",
"variable",
{
"testing": {
"testing": {
"something": "[replaceme]",
"testing": {
"testing": [
"[replaceme]",
"[replaceme]"
]
}
}
}
}
]
}
}
}
function parseObject(object, promises){
var keys = Object.keys(object);
for(let i = 0; i < keys.length; i++){
let item = object[keys[i]];
if(item instanceof Array){
for(let k = 0;k < item.length; k++){
if(typeof(item[k]) === "object") {
parseObject(item[k], promises);
}
else{
promises.push(
magicFunction(
item[k],
(newValue) => item[k] = newValue
)
);
}
}
}
else if(typeof(item) === "object")
parseObject(item, promises);
else
promises.push(magicFunction(item , (newValue) => object[keys[i]] = newValue));
}
return;
}
function magicFunction(item, defferedAssignment){
return new Promise(( resolve, reject ) => {
if(item === "[replaceme]") {
// Some ajax or misc
setTimeout(() => {
defferedAssignment("Replaced");
resolve()
}, Math.floor(Math.random() * 1000));
}
else {
defferedAssignment(item);
resolve()
}
});
}
var promises = [];
parseObject(object, promises);
Promise.all(promises).then(() => console.log(object))
I don't know if this is the best way to do it, but it works for me :).
You can wrap the allAll function in a function.
This also applies provided that the result of magicFunction does not return another [replaceme]. If these are not the desired parameters, it will require minor adjustments.
source to share