2

What I am looking to do is to use an array of strings to use those values to map a new array of promise functions for a Promise.all argument.

I think explains my thought process so far, as well as the issue I am running into.

const strings = ['A', 'B', 'C'] // Varies in size
const stringFunctions = strings.map(item => {
  const func = () => {
    promised(item) // Returns Promised Boolean
  }
  return func
})

const PromiseAll = new Promise(function(resolve, reject) {
  Promise.all(stringFunctions)
    .then(items => {
      const obj = {};
      items.forEach((item, index) => {
        obj[strings[index]] = item;
      });
      resolve(obj); 
      // returns { A: func(), B: func(), C: func() }
      // expected { A: bool, B: bool, C: bool }
    })
    .catch(error => {
      reject(error);
    });
}
ms_nitrogen
  • 240
  • 1
  • 14
  • `func` has a statement block but does not return anything. You need a `return` in there: `return promised(item)` – trincot Aug 19 '18 at 19:14
  • `Promise.all` does not take an array of promise functions, it takes an array of promises? – Bergi Aug 19 '18 at 19:21
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Aug 19 '18 at 19:22

1 Answers1

2

This can be done without any explicit promise creation (you have all you need in the promised function and in Promise.all()).

let strings = [ ... ]
let promises = strings.map(string => promised(string));
Promise.all(promises).then(results => {
    // results is a new array of results corresponding to the "promised" results
});
danh
  • 62,181
  • 10
  • 95
  • 136
  • 1
    Also if `promised()` is not a variadic function and takes exactly one argument, you can simplify that to `Promise.all(strings.map(promised)).then(results => { ... })` – Patrick Roberts Aug 19 '18 at 19:21
  • If I wanted to use the Promise.all for an `export`, I assume I'd name a `const P = promise.all(...); export default P`? I'm looking for the exported object results more than the promise itself. – ms_nitrogen Aug 19 '18 at 19:29
  • 1
    @ms_nitrogen - export something that is evaluated synchronously when the module loads (like a function or a class definition). It can provide an async function that the importer then invokes. – danh Aug 19 '18 at 19:32
  • @danh I wrapped it all up for a callback function, and it worked perfectly! Cheers! – ms_nitrogen Aug 19 '18 at 19:41