Home > Software engineering >  using async await with reduce
using async await with reduce

Time:12-01

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

CodePudding user response:

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);
}
  • Related