I am trying to use Promise.all with arrays of promise arrays such as below. But the sequence isn't as I expected. First, I create a promise to create a school, then I create three branches (creating students, creating teachers, creating courses); each creates an array of promises. Before I can continue; I must be sure that all promises resolved, because other models will be created assuming these are created.
I implemented the accepted solution here, but it didn't work.
Codepiece:
let studentPromises = [];
let teacherPromises = [];
let coursePromises = [];
createSchool = instance.post("/schools/", school);
//CREATE 10 STUDENTS
createSchool.then(() => {
for (let i = 0; i < 10; i++) {
const student = generatePerson();
studentPromises.push(instance.post("/students/", student));
}
Promise.all(studentPromises).then(() => {
console.log("Students are created");
});
});
//CREATE 3 TEACHERS
createSchool.then(() => {
for (let i = 0; i < 3; i++) {
const teacher = generatePerson();
teacherPromises.push(instance.post("/teachers/", teacher));
}
Promise.all(teacherPromises).then(() => {
console.log("Teachers are created");
});
});
//CREATE 6 COURSES
createSchool.then(() => {
for (let i = 0; i < 6; i++) {
const course = generateCourse();
coursePromises.push(instance.post("/courses/", course));
}
Promise.all(coursePromises).then(() => {
console.log("Courses are created");
});
});
Promise.all(
[studentPromises, coursePromises, teacherPromises].map(
Promise.all.bind(Promise)
)
).then(() => {
console.log("All done.");
});
Expected output:
- Students are created.
- Teachers are created.
- Courses are created.
- All done.
Reality:
- All done.
- Students are created.
- Teachers are created.
- Courses are created.