gpt4 book ai didi

javascript - 如何在 promise 中执行回调?

转载 作者:行者123 更新时间:2023-11-30 14:50:38 26 4
gpt4 key购买 nike

我这里有一个获取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)));

对于第二种方法,您基本上只是提供一个获取数据的函数,然后它会获取数据并以标准方式处理它。它还将创建一个函数来获取 reqres 本身。

关于javascript - 如何在 promise 中执行回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48153610/

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