Josh
Josh

Reputation: 3120

How do I make this an asynchronous hook?

How do I make this function wait for the promise to resolve in each nested for loop so I can set the relations for each collection? The exercise names are printed after the context log.

        find: [
            function (context) {
                context.result.data.forEach((workout) => {
                    workout.exercises.forEach((exercise) => {
                        context.app.service('exercises').get(exercise.exerciseId).then((data) => {
                            exercise.name = data.name;
                        });
                    });
                });

                console.log(context.result.data[0]);

                context.dispatch = context.result;
                return context;
            }
        ],

Relations are: workout has many exercises and exercise has 1 name.

Upvotes: 0

Views: 509

Answers (1)

Daff
Daff

Reputation: 44215

When iterating over several asynchronous tasks Promise.all and Array.map is your friend:

async function (context) {
    await Promise.all(context.result.data.map((workout) => {
        return Promise.all(workout.exercises.map((exercise) => {
            return context.app.service('exercises').get(exercise.exerciseId).then((data) => {
                exercise.name = data.name;
            });
        });
    });

    console.log(context.result.data[0]);

    context.dispatch = context.result;
    return context;
}

Upvotes: 1

Related Questions