1

Seem to be having some type issue by using async/await with .reduce()

I have to call one async function inside the reduce with proper types but I can't figure out why Anyone pls help me

interface Person {
  name: string;
  age: number;
}

const persons: Person[] = [
  { name: 'John', age: 30 },
  { name: 'Alice', age: 45 },
];

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

const ageByPerson: Person[] = persons.reduce<Person[]>(
  async (result, person) => {
    await sleep(4000);
    return result.concat({
      age: person.age,
      name: person.name,
    });
  },
  []
);
console.log('age ', ageByPerson);

Without interface is working fine But when I am using with interface I can't figure it out

1
  • 1
    Array#reduce doesn't support promises. Wrap it in a Promise.all(...) Commented Feb 21, 2022 at 3:58

1 Answer 1

5

Since the callback is async, it'll always return a Promise; the type parameter should not be Person[], but Promise<Person[]>. You also need to pass such a value as the initial value, and wait for the prior accumulator to resolve before concating.

const ageByPersonPromise = persons.reduce<Promise<Person[]>>(
    async (resultPromise, person) => {
        const result = await resultPromise;
        await sleep(4000);
        return result.concat({
            age: person.age,
            name: person.name,
        });
    },
    Promise.resolve([])
);
ageByPersonPromise
    .then((ageByPerson) => {
        console.log('age ', ageByPerson);
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.