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);
    });
}
3
  • func has a statement block but does not return anything. You need a return in there: return promised(item) Commented Aug 19, 2018 at 19:14
  • Promise.all does not take an array of promise functions, it takes an array of promises? Commented Aug 19, 2018 at 19:21
  • Avoid the Promise constructor antipattern! Commented Aug 19, 2018 at 19:22

1 Answer 1

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
});
Sign up to request clarification or add additional context in comments.

4 Comments

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 => { ... })
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 - 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 I wrapped it all up for a callback function, and it worked perfectly! Cheers!

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.