I'm doing multiple fetchs with Promise.all
. So I receive data like this :
[
0: {
...
},
1: {
...
}
]
But I would like to name my Objects. So I can do data.myObject
istead of data[0]
.
I would like the index to be a string that I chose. For example, i'd like to get :
[
"home": {
...
},
"product": {
...
}
]
Is is possible ? Thanks
CodePudding user response:
No, this is not possible. Promise.all
works on iterables (like arrays), not on objects. Name your values after the Promise.all
call:
const data = await Promise.all([…, …]);
const home = data[0], product = data[1];
becomes with destructuring
const [home, product] = await Promise.all([…, …]);
CodePudding user response:
Promise.all
works with an array. Arrays deal in numerically indexed (ordered) values.
You'd need to have a name stored somewhere for each promise, and then generate the object from them once the promises had resolved.
e.g.
const names = ['home', 'product'];
const promises = [fetchHome(), fetchProduct()];
const results = await Promise.all(promises);
const resultsByName = names.reduce((prev, curr, index) => {
return {...prev, [curr]: results[index]};
}, {});
You could use a similar approach without the second array if the name was available in the resolved values of fetchHome()
and fetchProduct()
.
CodePudding user response:
You can destructure the array of Promise results in the Promise.all.
const [home, product, toolbar, nav] = await Promise.all([
getHome(), getProduct(), getToolBar(), getNav()
]);
Since the results are an array like anything else you can destructure arrays and even use the ...rest syntax:
const [home, product, toolbar, nav, ...otherPromises] = await Promise.all([
getHome(), getProduct(), getToolBar(), getNav(), getOtherThing1()
]);
// otherPromises will be an array that you'll have to access
// with numeric keys as before:
// eg. otherPromises[0] might be the first non-named promise
// the result of getOtherThing1()
CodePudding user response:
Seems like you want to convert Array to an object so you can get data by calling a key.
const arr = [ { id: "home", val: "val1" }, { id: "product", val: "val2" }];
const convert = arr.reduce((a,b) => (a[b.id] ??= b,a),{});
console.log(convert);
console.log(convert.home);