-1

i have following

const imageField = ["logoUrl", "fullLogoUrl"]
const onCreate = async (submitData: any) => {
  const uploadImageField = await imageField.reduce(
    async function (acc: any, cur: string) {
      await acc;
      const url = await uploadImage(submitData.general[cur][0]);
      acc[cur] = url;
      return acc;
    },
  {}
);

console.log(uploadImageField);
}

this is my console.log

{
  logoUrl: "https://........"
}

only logoUrl field is show, fullLogoUrl is missing

  • reduce, much like forEach and map, will not wait on the promise to resolve before it continues. – Kevin B Nov 30 '21 at 19:38
  • 1
    i would map over the list of images, produce a list of promises, and await all of them (Promise.all or something) – akaphenom Nov 30 '21 at 19:41

1 Answers1

0

The problem is that acc on the second iteration is a promise object - that's why you await it. However, you still assign the [cur] property on that promise object, not on the promise result, and the implicit promise chaining of the async function as well as the explicit awaits will just ignore properties on the promise object. You could fix this by doing acc = await acc;, but really I recommend not to use reduce with async/await at all. A normal loop is much simpler and has no pitfalls.

const imageField = ["logoUrl", "fullLogoUrl"]
const onCreate = async (submitData: any) => {
  const uploadImageField = {};
  for (const cur of imageField) {
      const url = await uploadImage(submitData.general[cur][0]);
      acc[cur] = url;
  }
  console.log(uploadImageField);
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375