如何 运行 这些承诺按顺序排列
How to run these promises in order
所以下面的代码将向您展示我正在尝试从文件中读取运动员和部门。
一个部门有一个运动员名单,所以首先我想映射该部门的每个运动员并将该运动员名单分配给该部门。控制台日志显示如下:假设每个部门各有 5 名运动员。
所以我希望 console.log("TEST_1")
打印 5 次,console.log("TEST_2")
打印 1 次,每个部门都这样。
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..............
}
但是这段代码所做的是:打印所有“TEST_1”,然后才打印“TEST_2”,因此它将最后 5 名运动员放在所有部门中。
我尝试更改 async
和 await
但它不起作用...
你能帮帮我吗?
我不确定我是否理解代码的实际作用。另外我认为你错过了使用“await”可以让你免于使用 Promises 中的 .then() 和 .catch()。但我猜你必须将其更改为:
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..............
}
所以下面的代码将向您展示我正在尝试从文件中读取运动员和部门。
一个部门有一个运动员名单,所以首先我想映射该部门的每个运动员并将该运动员名单分配给该部门。控制台日志显示如下:假设每个部门各有 5 名运动员。
所以我希望 console.log("TEST_1")
打印 5 次,console.log("TEST_2")
打印 1 次,每个部门都这样。
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..............
}
但是这段代码所做的是:打印所有“TEST_1”,然后才打印“TEST_2”,因此它将最后 5 名运动员放在所有部门中。
我尝试更改 async
和 await
但它不起作用...
你能帮帮我吗?
我不确定我是否理解代码的实际作用。另外我认为你错过了使用“await”可以让你免于使用 Promises 中的 .then() 和 .catch()。但我猜你必须将其更改为:
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..............
}