Node js返回请求响应从另一个/子函数?



我有一个async方法,在async方法内我调用另一个函数。所以我只是想,如果另一个函数不存在数据,然后想从另一个函数返回响应。

请遵循以下示例:

async function generate_lineup(req, res) {
var email = req.body.email;
check(email); // it handle global varibale & push data

database.insertdata();
}
async function check email(email) {
// if error or email already exist then return from here
return res.status(404).json({'status':'failed','message':'email already exist'});
}

有两种方法:
最直接的方法是将res对象传递给checkEmail函数

async function generate_lineup(req, res) {
var email = req.body.email;
check(email,res);
}
async function checkEmail(email,res) {
// if error or email already exist then return from here
return res.status(404).json({'status':'failed','message':'email already exist'});
}

更好的方法是避免这种情况,并在"控制器"内部处理响应逻辑。这取决于checkEmail函数返回的内容(它的返回值可以更改为对象以适应更多场景)

最好这样做:

async function generate_lineup(req, res) {
var email = req.body.email;
try {
await check(email);
return res.json({'status':'success'});
} catch(e) {
return res.status(404).json({'status':'failed','message':e.message});
}
}
async function check(email) {
// if error or email already exist then return from here
throw new Error('email already exist');
}

async function generate_lineup(req, res) {
var email = req.body.email;
return await check(email);
}
async function check email(email) {
// if error or email already exist then return from here
return res.status(404).json({'status':'failed','message':'email already exist'});
}

就像这样?

更新

async function generate_lineup(req, res) {
var email = req.body.email;
const res = await check(email);
if (res.stausCode === 404) return res;
database.insertdata();
}
async function check email(email) {
// if error or email already exist then return from here
return res.status(404).json({'status':'failed','message':'email already exist'});
}

最新更新