这是我的nodejs api代码:
exports.createBusiness = (req, res) => {
const business = { name: req.body.name };
Business.create(business)
.then(() => {
createSchema() // this function, i pasted below
.then(() => {
console.log('6 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
});
})
.catch((err) => {
console.log('err:', err);
});
};
我的功能:
const createSchema = () => Business.findAll({
raw: true,
}).then((data) => {
console.log('1 >>>>>>>>>>>>>>>>>>>>>>>>>>>>');
data.forEach((client) => {
console.log('2 >>>>>>>>>>>>>>>>>>>>>>>>>>>>');
postgresDB.createSchema(client.code).then(() => {
console.log('3 >>>>>>>>>>>>>>>>>>>>>>>>>>>>');
Object.keys(postgresDB.models).forEach((currentItem) => {
console.log('4 >>>>>>>>>>>>>>>>>>>>>>>>>>>>');
postgresDB.models[currentItem].schema(client.code).sync();
console.log('5 >>>>>>>>>>>>>>>>>>>>>>>>>>>>');
});
console.log('Postgres schema created');
});
});
}).catch((err) => {
console.log('Warning:', err.message);
});
我的输出现在按以下顺序进入控制台:
1
2
2
2
2
2
2
2
2
2
6
3
4
5
我的预期输出将在控制台中:(我需要同步执行):
1
2
2
2
2
2
2
2
2
2
3
4
5
6
如何使用promise或callbacks使它同步运行?
我尝试了promise.all但没有用,还是异步等待很好处理?
答案 0 :(得分:0)
您需要createSchema
返回的诺言才能解决所有其他诺言。将每个map
client
到Promise
,然后在其上调用Promise.all
。您还需要将每个currentItem
映射到Promise
并在该Promises数组上也调用Promise.all
。
由于console.log
,看起来有点难看:
const createSchema = () => Business.findAll({
raw: true,
}).then((data) => {
console.log('1 >>>>>>>>>>>>>>>>>>>>>>>>>>>>');
const clientPromises = data.map(({ code }) => {
console.log('2 >>>>>>>>>>>>>>>>>>>>>>>>>>>>');
return postgresDB.createSchema(code).then(() => {
console.log('3 >>>>>>>>>>>>>>>>>>>>>>>>>>>>');
return Promise.all(Object.values(postgresDB.models).map(item => {
console.log('4 >>>>>>>>>>>>>>>>>>>>>>>>>>>>');
return item.schema(code).sync()
.then(() => console.log('5 >>>>>>>>>>>>>>>>>>>>>>>>>>>>'));
}))
.then(() => console.log('Postgres schema created'));
});
});
return Promise.all(clientPromises);
}).catch((err) => {
console.log('Warning:', err.message);
});
如果没有console.log
,看起来会更干净:
const createSchema = async () => {
try {
const data = await Business.findAll({ raw: true });
const clientPromises = data.map(async ({ code }) => {
await postgresDB.createSchema(code);
return Promise.all(Object.values(postgresDB.models).map(item => (
item.schema(code).sync()
)));
});
return Promise.all(clientPromises);
} catch (e) {
console.log('Warning:', e);
}
};