node.js - 异步等待然后在同一个函数上

标签 node.js express asynchronous controller sequelize.js

有没有更好的方法用 Sequelize 做到这一点?
关键是,我怎么知道更新是否在不使用 .then 和 .catch 的情况下工作,因为我已经在使用 inside 和 async 函数,我需要验证更新是否真的有效。

async update(req, res) {
        const owner = await Owner.findByPk(req.params.ownerId);

        if (owner) {
            const { name, email, password, type } = req.body;
        
            owner.update({ name, email, password, type })
                .then(result => {
                    return res.json({ status: 'success', message: 'Owner updated' });
                })
                .catch(err => {
                    return res.status(500).json({ status: 'error', message: err });
                });
        }

        return res.status(404).json({ status: 'not found', message: 'Owner not found' });
    },

最佳答案

改用 async/await 语法

try {
  await owner.update({ name, email, password, type });
  return res.json({ status: 'success', message: 'Owner updated' });
} catch (err) {
  return res.status(500).json({ status: 'error', message: err });
}

关于node.js - 异步等待然后在同一个函数上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62905229/

相关文章:

node.js - Sequelize 不为多对多关系创建连接表

node.js - 如何在 Node 应用程序中使用 Materialise Toast

node.js - 从 Azure Blob 存储下载文件的示例

javascript - 在同步回调函数中等待异步回调函数

node.js - Nodemailer 无法使用 gmail 发送邮件

node.js - Windows 上监听 1880 端口失败

javascript - 如何在 node.js 中使用堆栈跟踪记录错误?

node.js - 使用 Hapi.JS Joi 模块在 Express.JS 应用程序中验证和清理输入之间的区别?

C# 异步 UDP 监听器 SocketException

c# - 机器人框架 : Loop through Prompts