![](/img/trans.png)
[英]JS Promises: Why does await have to be inside an async function?
[英]Promises => Async/Await…Does this have any benefits?
我正在通过快速服务器控制器进行工作,并从promises
重构为async/await
。 对于某些功能,我不确定是否只是为了它而这样做。 如果它不可读,我还是应该这样做吗?
这是一个例子:
async sharedTroop(req, res, next) {
const firebaseUID = req.params.uid;
try {
const user = await User.findOne({ firebaseUID }).select('troopPointTotal');
user.troopPointTotal += 1000;
try {
user.save();
try {
res.send(user);
} catch (e) {
next(e);
}
} catch (e) {
next(e);
}
} catch (e) {
next(e);
}
}
上面的内容(使用async/await
)是否对此有任何好处?:
sharedTroop(req, res, next) {
const firebaseUID = req.params.uid;
User.findOne({ firebaseUID })
.select('troopPointTotal')
.then(user => {
user.troopPointTotal += 1000;
user.save().then(() => res.send(user));
})
.catch(next);
},
而且如果重构没有提高可读性,我是否应该打扰?
谢谢!
没有理由嵌套try
语句:
async sharedTroop(req, res, next) {
const firebaseUID = req.params.uid;
try {
const user = await User.findOne({ firebaseUID }).select('troopPointTotal');
user.troopPointTotal += 1000;
user.save();
res.send(user);
} catch(e) {
next(e);
}
}
这看起来比then
解决方案的嵌套回调好得多。 它还简化了错误的user.save()
:您将要在发送响应之前await
user.save()
的结果-然后catch
将隐式处理保存过程中的错误。 相反,你then
版本都有一个类似的错误:通过不return
荷兰国际集团的结果user.save().then(() => res.send(user))
从回调,错误将不会被处理.catch()
到底。
如果重构没有提高可读性,我是否应该打扰?
当然,可读性是主观的,如果您认为没有优势,那么您就不应该费心去做反应堆。
简短的回答不, async/await
只是您使用then / catch
编写的代码的语法糖。
唯一的好处就是让您眼前一亮。 无需回调,您可以模仿“同步”代码样式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.