I have an array of objects which some of the items within it has a "logo" object containing a key of an image stored on a S3 Bucket.
This is an optional field, so sometimes it doesn't exist in the object. To retrieve the image, I am using the Storage api from AWS-Amplify. This Storage function returns me a promise and here is my first problem.
const fetchUsers = async () => {
setLoading(true);
const formatedData = [];
const { data } = await API.graphql(graphqlOperation(listUsers));
console.log({ data });
data.listUsers.items.map(async user => {
if (user.logo) {
console.log(Storage.get());
const image = await Storage.get(user.logo.key);
user.image = image;
formatedData.push(user);
} else {
formatedData.push(user);
}
})
}
While I am waiting the response for the response from the Storage.get function, the loop keep running, which is modifying the original sorting that came from the data array.
This is causing all the entries that has images are appearing at last on the array.
So given this, I assume that
- There's a way to prevent the loop to run while I am still waiting for the response
- There's a better/more efficient way to get these images from S3.
Any thoughts how to make it run more smoothly ?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…