【发布时间】:2018-12-02 12:45:33
【问题描述】:
我的nodejs api函数:
exports.userSignup = (req, res) => {
const home = {
address: req.body.name,
phoneno: req.body.code,
};
Home.create(home)
.then((data) => {
createUser()
// i want to complete the above createUser() function fully then only i need to move to this below then function
.then(() => {
const loginDetails = {
username: 'stackoverflow',
};
User.create(loginDetails)
.then((data) => {
return res.status(200).send(data);
}).catch((err) => {
console.log('error while create schema:', err);
});
});
})
.catch((err) => {
console.log('err:', err);
});
};
我的createUser函数代码:
const createUser = () => {
Home.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((err) => {
console.log(err);
});
});
}).catch((err) => {
console.log('Warning:', err.message);
});
};
createUser();
但是这个是异步的,
如何使用 Promise 解决拒绝或回调?
查看我的代码,我做了一个需要先工作的评论,
我尝试了异步等待但不工作!
【问题讨论】:
-
更新了我的答案。没有注意到您正在 for 循环中执行异步函数调用。片段应该可以工作。
-
没有异步代码会同步工作。您需要调整您的
forEach循环
标签: javascript node.js asynchronous callback promise