Search code examples
javascriptasynchronouspromiseasync-awaites6-promise

Promise in promise


How to handle next promise problem situation: I need to resolve pets for each person, fire event after pets is resolved and fire last event when all persons are resolved:

(async() => {
    const personsArr = await Promise.all(persons.map(async (person) => {
        await someSyncFunc();
        const petsArr = await Promise.all(pets.map(async (pet) => {
          await asyncSetPetName(pet, person);
        }));
        Promise.resolve(petsArr)
            .then(async () => someSyncFunc());
            .then(() => console.log('pets resolved'));
    }));
    Promise.resolve(personsArr)
        .then(async  () => someSyncFunc());
        .then(() => console.log('persons resolved'));
})();

Problem is first Promise.resolve is count for personsArr.


Solution

  • That Promise.resolve(arr).then(…) doesn't make any sense. Not only is arr already an array (nothing that needs to be resolved), but also you shouldn't use then when working with async/await:

    (async() => {
        const personsArr = await Promise.all(persons.map(async (person) => {
            const petsArr = await Promise.all(pets.map(async (pet) => {
                return asyncSetPetName(pet, person);
            }));
            console.log('pets resolved');
        }));
        console.log('persons resolved');
    })();