1

Running Node v 8+, along with bluebird and lodash libraries.

Here is an array of fake objects:

const theList = [
{name: 'foo'
 values: [ promise, promise, promise ] },
{name: 'bar',
 values: [ promise ] }
];

How do i write promise resolvers such that I can iterate the entire array of objects, and resolve the property containing the array of promises? Each promise will resolve as an array of objects... thus it could wind up looking like: [ [resolvedObj1], [resolvedObj1,resolvedObj2,resolvedObj3], [resolvedObj1, resolvedObj2] ]

I'd like them all to resolve such that I have an object of the following:

let resolved = [
 {name: 'foo',
  values: [resolved, resolved, resolved, resolved, resolved]},
 {name: 'bar',
  values: [resolved]}
];

Here was my current solution:

const resolvedCollection= await Promise.map(theList, async obj=> {
  const resolved = await Promise.all(obj.values);
  obj.values = _.flatten(resolved);  // lodash "flatten" function
  return obj;
});

Is there a cleaner way to do this? Also maybe a way in which I need not hardcode the values property of each object iterated on?

1 Answer 1

2

Your approach seems pretty clean. Here is how I would write it:

const theList = [
    {
      name: 'foo',
      values: [ promise, promise, promise ]
    },
    {
      name: 'bar',
      values: [ promise ]
    }
];

theList.map(item => 
  ({
    ...item, 
    values: _.flatten(await Promise.all(item.values))
  })
)

Furthermore, you could trivially replace the flatten function without any recursion since it's just two levels.

[[1], [2, 3], [4, 5]].reduce((a, b) => [...a, ...b])

Which, applied to the original solution would look like this:

theList.map(item => 
  ({
    ...item, 
    values: (await Promise.all(item.values).reduce((a, b) => [...a, ...b]))
  })
)

Very well formulated question.

Sign up to request clarification or add additional context in comments.

1 Comment

Good stuff! Thanks for taking the time to answer this and help me out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.