gpt4 book ai didi

javascript - 将 async/await 转换为 Promise 链

转载 作者:行者123 更新时间:2023-11-28 16:54:28 25 4
gpt4 key购买 nike

我有这段代码,我正在尝试创建一个新用户,加密密码并尝试通过 mongoose 将用户保存在 MongoDB 中。

有什么方法可以改变这个 async/await 来 promise 链接吗?

user = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
user.password = await bcrypt.hash(user.password, 10);
await user.save();

const token = user.generateAuthToken();
res.header("x-auth-token", token).send({
_id: user._id,
name: user.name,
email: user.email
});
});

最佳答案

你应该能够做这样的事情:

  user = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
bcrypt.hash(user.password, 10)
.then(pw => { user.password = pw; return user.save(); })
.then(() => { ...rest of the function here...});

关于javascript - 将 async/await 转换为 Promise 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59465931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com