作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我这里有一个获取Section
的函数。它返回一个 Promise
router.get('/menu_section', (req, res) => {
Section.read(req.body)
.then(d => {
send(d, res);
})
.catch(e => {
error(e, res);
});
});
有没有办法在我处理 Promise
时减少 then
catch
样板代码?我希望以这种方式编写它以减少样板。
router.get('/menu_section', (req, res) => {
Section.read(req.body).respond(data, err, res)
});
//handle it in this way for all routes.
function respond(data, err, res){
if(err) res.data({err})
else res.json({data});
}
编辑:我想避免为每个 Promise 句柄编写 then
catch
最佳答案
你将无法完全按照你提到的去做(如果不覆盖 Promise
,这通常是不受欢迎的)。
但是您可以创建一个简单的包装函数来为您完成:
function respond(promise, res) {
promise
.then(data) => res.data(data))
.catch(err => res.data({err})
}
router.get('/menu_section', (req, res) => {
respond(Section.read(req.body), res);
});
您甚至可以将其归结为如下内容:
function respond(getData) {
return (req, res) => {
getData(req)
.then(data) => res.data(data))
.catch(err => res.data({err})
};
}
router.get('/menu_section', respond(req => Section.read(req.body)));
对于第二种方法,您基本上只是提供一个获取数据的函数,然后它会获取数据并以标准方式处理它。它还将创建一个函数来获取 req
和 res
本身。
关于javascript - 如何在 promise 中执行回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48153610/
我是一名优秀的程序员,十分优秀!