在我的nodejs应用中,我在路由/ restapi中使用了一些子功能。
此子功能之一看起来像:
console.log("Before Oauth");
await checkTheUser(clipApiID + ':' + clipApiSecret).then(res2 => {
console.log( "Success: " + res2 );
}).catch(error => {
console.log('Oauth Fehler');
//stop the route
res.statusCode = 409; //Wrong validation
res.json({
success: 'Wrong validation',
fails: 0
});
//End stop the route
});
console.log("After Oauth");
我希望该路径将在发生错误并发送res后结束。但最终,这条路线走得更远直到终点。
我在发送res后也尝试过"return false"
,但路由也继续运行。
//stop the route
res.statusCode = 409; //Wrong validation
res.json({
success: 'Wrong validation',
fails: 0
});
return false;
//End stop the route
我添加了“ OAuth之前”和“ OAuth之后”消息,以检查是否存在异步问题。但是日志显示:
最后我尝试了下一个并添加了
app.use(function(err, req, res, next) {
console.error(err.message); // Log error message in our server's console
if (!err.statusCode) err.statusCode = 500;
res.status(err.statusCode).json({
success: err.message,
fails: 0
});
});
和使用
//stop the route
let err = new Error(`Oauth Error`); /
err.statusCode = 401;
return next(err);
//End stop the route
我很困惑,此解决方案中没有人会停止路由以进一步执行。知道我做错了吗?
为什么要等待,然后再编写.then和.catch?你的意思是
我预计该路线将在发生错误后结束,并且res已发送。但最终,这条路线一直走到尽头。
我认为您误解了等待。你可以写
checkTheUser(clipApiID + ':' + clipApiSecret).then(dataInvokedInPromiseResolve=> {
console.log( "Success: " + dataInvokedInPromiseResolve);
}).catch(error => {console.log(error)}
或使用声明为异步的函数
try {
dataInvokedInPromiseResolve = await checkTheUser(clipApiID + ':' + clipApiSecret);
console.log( "Success: " + dataInvokedInPromiseResolve);
}catch (err) {console.log(err)}//don't forget to catch
结束并停止路线
.catch(error => {
console.log('Oauth Fehler');
//stop the route
res.statusCode = 409; //Wrong validation
res.json({
success: 'Wrong validation',
fails: 0
});
return //add your return
}