How to run these promises in order

So the code below will show you that I am trying to read athelets and departments from a file.

A department has a list of athletes, so first I want to map each athlete of that department and assign that list of athletes to the department. The console logs are there to show the following: imagine that each department has 5 athletes each.

So I want the console.log("TEST_1") to print 5 times and console.log("TEST_2") to print 1 time, all of this for each department.

var array1 = [];
await Promise.all(departaments.map(async dp => {

        array1 = [];
        await Promise.all(athletes.map(async at => {

            var athlete = new Athlete();
            athlete.name = at.name;
            athlete.weight = at.weight;

            array1.push(athlete._id);
            athlete.save();
                        console.log("TEST_1");

        })).then(() => {

            var dep = new Department();
            dep.name = dp.name;
            Object.assign(dep.athletes, array1);

            dep.save();
            console.log("TEST2");
        });
    })).then(async () => {
    ............not relevant..............
}

But what this code is doing is: printing all the "TEST_1" and only then "TEST_2" therefore it places the last 5 atheletes in all departments.

I tried changing the async and the await but it doesn't work...

Can you please help me?

1 answer

  • answered 2020-11-25 00:39 spaxxUnited

    I am not sure i understand what the code actually does. Also i think you missed that using "await" frees you from using .then() and .catch() from Promises. But i'd guess you'd have to change it to:

    var array1 = [];
    await Promise.all(departaments.map(async dp => {
    
            array1 = [];
            await Promise.all(athletes.map(async at => {
    
                var athlete = new Athlete();
                athlete.name = at.name;
                athlete.weight = at.weight;
    
                await athlete.save();
    
                // maybe wait till the ORM's .save() operation provides an id?
                array1.push(athlete._id);
    
                            console.log("TEST_1");
    
            }));
    
            var dep = new Department();
            dep.name = dp.name;
            Object.assign(dep.athletes, array1);    
    
            await dep.save();
    
            console.log("TEST2");
    
        })).then(async () => {
        ............not relevant..............
    }