-1

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);
      });
    }
thecolin
  • 21
  • 4
  • [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) is probably what you are looking for. – basic Mar 19 '19 at 13:52
  • Possible duplicate of [Wait until all ES6 promises complete, even rejected promises](https://stackoverflow.com/questions/31424561/wait-until-all-es6-promises-complete-even-rejected-promises) – basic Mar 19 '19 at 13:53
  • "* I know I should be able to use `Promise.all` and pass in an array of the promises I have created*" - yes, you should try that. In your code I see neither an array of promises nor a call to `Promise.all`. Where did you attempt to place them? – Bergi Mar 19 '19 at 14:49

1 Answers1

1

First, you can map the data into a map of promises, then, after been resolved, reduce them into an object:

Promise.all(data.dock.map(({url}) => getDockData(url, user_token)))
    .then(res => res.reduce((acc, curr) => ({...acc, ...curr}), {}))
    .then(compedObj => /* do something with the result data */);
ttulka
  • 10,309
  • 7
  • 41
  • 52