I could use some help identifying when all Javascript promises have resolved. I am looping through an array of objects and for each object I call a function which returns a promise. Each promise resolves into an object, and I merge these objects together to create one large object. I want to do something when I know this large object is complete i.e. when all the promises have resolved. I know I should be able to use Promise.all and pass in an array of the promises I have created but I am struggling to achieve this in code. Any help you be much appreciated. Here is my code:
let data = JSON.parse(body)
let compedObj = {}
for (let i=0;i<data.dock.length;i++) {
getDockData(data.dock[i].url, user_token)
.then (data => {
compedObj = {...compedObj, ...data}
})
}
function getDockData (url, token) {
return new Promise((resolve, reject)=>{
var options = {
url: url,
headers: {
'authorization': `bearer ${token}`,
'user-agent': /* my app details */
}
}
function callback(error, response, body) {
if (!error) {
let data = JSON.parse(body)
let obj = {}
switch(data.title) {
case "ToDos":
obj = {todos: data.todos_count};
break;
case "Messages":
obj = {messages: data.messages_count}
break;
}
resolve(obj)
} else {
reject("there was an error")
}
}
Request(options, callback);
});
}