2

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:

  1. Students are created.
  2. Teachers are created.
  3. Courses are created.
  4. All done.

Reality:

  1. All done.
  2. Students are created.
  3. Teachers are created.
  4. Courses are created.
Edaz
  • 300
  • 1
  • 6
  • 16
Özhan Efe Meral
  • 128
  • 1
  • 10
  • 1
    `studentPromises` and the other arrays are populated asynchronously, so with `Promise.all([studentPromises, ...`, the mapped and passed array of arrays has no inner items. Put everything inside a single `createSchool.then` callback – CertainPerformance Mar 14 '20 at 05:28
  • worked like a charm! thank you very much for your quick answer and proper link. – Özhan Efe Meral Mar 14 '20 at 05:32

0 Answers0