I have an array like structure that exposes async methods. The async method calls return array structures that in turn expose more async methods. I am creating another JSON object to store values obtained from this structure and so I need to be careful about keeping track of references in callbacks.
I have coded a brute force solution, but I would like to learn a more idiomatic or clean solution.
- The pattern should be repeatable for n levels of nesting.
- I need to use promise.all or some similar technique to determine when to resolve the enclosing routine.
- Not every element will necessarily involve making an async call. So in a nested promise.all I can't simply make assignments to my JSON array elements based on index. Nevertheless, I do need to use something like promise.all in the nested forEach to ensure that all property assignments have been made prior to resolving the enclosing routine.
- I am using the bluebird promise lib but this is not a requirement
Here is some partial code -
var jsonItems = [];
items.forEach(function(item){
var jsonItem = {};
jsonItem.name = item.name;
item.getThings().then(function(things){
// or Promise.all(allItemGetThingCalls, function(things){
things.forEach(function(thing, index){
jsonItems[index].thingName = thing.name;
if(thing.type === 'file'){
thing.getFile().then(function(file){ //or promise.all?
jsonItems[index].filesize = file.getSize();
Promise.map
(concurrent) andPromise.each
(sequential) in this case, also notePromise.defer
is deprecated - the code in my answer shows how to avoid it by returning promises. Promises are all about return values. – Lighthouse