How to map an array of strings for a Promise.all argument?

How to map an array of strings for a Promise.all argument?



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);
);





func has a statement block but does not return anything. You need a return in there: return promised(item)
– trincot
Aug 19 at 19:14



func


return


return promised(item)





Promise.all does not take an array of promise functions, it takes an array of promises?
– Bergi
Aug 19 at 19:21



Promise.all





Avoid the Promise constructor antipattern!
– Bergi
Aug 19 at 19:22


Promise




1 Answer
1



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


promised


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
);





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 at 19:21


promised()


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
Aug 19 at 19:29



export


const P = promise.all(...); export default P





@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 at 19:32






@danh I wrapped it all up for a callback function, and it worked perfectly! Cheers!
– ms_nitrogen
Aug 19 at 19:41






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Help:Category

How can temperature be calculated given relative humidity and dew point?

I have a recursive function to validate tree graph and need a return condition