Javascript 如何在承诺中执行回调?
我这里有一个函数,它得到一个Javascript 如何在承诺中执行回调?,javascript,node.js,Javascript,Node.js,我这里有一个函数,它得到一个部分。它返回一个承诺 router.get('/menu_section', (req, res) => { Section.read(req.body) .then(d => { send(d, res); }) .catch(e => { error(e, res); }); }); 有没有一种方法,在我处理承诺的同时,我可以
部分
。它返回一个承诺
router.get('/menu_section', (req, res) => {
Section.read(req.body)
.then(d => {
send(d, res);
})
.catch(e => {
error(e, res);
});
});
有没有一种方法,在我处理承诺
的同时,我可以减少然后
捕获
样板代码?我希望以这种方式写它,以减少锅炉板
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});
}
编辑:我想避免为每个承诺句柄编写,然后
捕获
,可能是咖喱?:
const respond = res => data => {
res.json(data);
};
因此,您可以:
router.get('/menu_section', (req, res) => {
Section.read(req.body).catch(e => e).then(respond(res));
});
但是,我会直接用它制作一个中间件:
const respond = (req, res, next) => {
Section.read(req.body).then(
data => res.json(data),
err => next(err)
);
};
所以你可以
router.get('/menu_section', respond);
请注意,
async
/await
在这里很有用:
router.get('/menu_section', async (req, res) => {
try {
res.json(await Section.read(req.body));
} catch(e) {
res.json(e);
}
});
你不能完全按照你所说的去做(如果不推翻通常不赞成的
承诺
)
但是,您可以创建一个简单的包装函数来为您执行此操作:
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
本身。如果您希望以这种方式响应所有路由,可以在应用程序范围内使用它
app.use((req, res, next) => (
Section.read(req.body)
.then(d => send(d, res))
.catch(e => error(e, res));
)
您也可以在每个路由的基础上,甚至每个文件(包含多个路由)使用此函数。看起来您正在使用库进行路由,对吗?@NielsdeBruin是的。我希望避免为每个函数编写
然后或catch
。我想对所有路线进行一般处理。因此,承诺的响应将被单个承诺处理程序捕获,我将在其中定义然后或捕获。使用Async/Await还介绍了我编写一些样板编辑:类似于@samanime的解决方案