我正在使用 nodejs
这是我的名为 createSchema 的函数:
const createSchema = () => {
Business.findAll({
raw: true,
}).then((data) => {
data.forEach((client) => {
postgresDB.createSchema(client.code).then(() => {
Object.keys(postgresDB.models).forEach((currentItem) => {
postgresDB.models[currentItem].schema(client.code).sync();
});
console.log('Postgres schema created');
}).catch(() => {
});
});
}).catch((err) => {
console.log('Warning:', err.message);
});
};
createSchema();
我在这个 post 函数中调用这个函数
exports.createBusiness = (req, res) => {
const business = {
name: req.body.name,
code: req.body.code,
email: req.body.email,
};
Business.create(business)
.then((rawbusinessData) => {
createSchema() // this is the function
.then(() => { . // i want to complete createSchema fully then only i want to execute this below stuffs
const businessData = rawbusinessData.get({ plain: true });
const loginDetails = {
username: 'sameer',
password: encrypt('sameer'),
};
const schemaLogin = postgresDB.models.login.schema(businessData.code);
schemaLogin.create(loginDetails).then((loginData) => {
console.log('loginData:', loginData);
});
res.status(200).send(businessData);
});
})
.catch((err) => {
console.log('err:', err);
});
};
我在名为 createBusiness 的第二个 post 函数中调用第一个函数,
我想完全完成 createSchema 函数,那么只需要在我的第二个函数 createBusiness 中执行其他 then 方法()
查看我的代码,我做了一个评论需要先工作,
我尝试使用 async await 但没有用!
最佳答案
您在很多地方都缺少返回 Promise。您需要归还所有这些:
// No "block" implies return
const createSchema = () =>
Business.findAll({ raw: true})
.then((data) =>
// wrap Promise.all and map() instead of forEach()
Promise.all(
data.map((client) =>
postgresDB.createSchema(client.code).then(() =>
// Again wrap Promise.all and map()
Promise.all(
Object.keys(postgresDB.models).map((currentItem) =>
postgresDB.models[currentItem].schema(client.code).sync()
)
)
)
)
)
)
.then(() => console.log("now I'm done"))
//.catch((err) => console.log('Warning:', err.message));
所以主要是包装 Promise.all
并使用 Array.map()
实际返回你正在迭代的 promise
另一件事是不要过度使用 block {}
。无论如何,当你只有一个东西时,只需返回箭头函数即可。可选择删除 .catch()
并只允许抛出此函数的错误。调试之后,您实际上“应该”删除该行并允许抛出错误。
关于javascript - 使异步代码像同步一样工作 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50738207/