[英]catch block is not called with async/await
当我的互联网连接关闭时,我只是想获取一些数据。 所以节点获取拒绝了我返回的承诺。 但问题是我的代码没有停止,也没有调用 catch 块。 它只是继续执行到下一行。
我的代码与 try catch 块:
router.get("/test" , async (req , res , next) => {
try {
let params = new URLSearchParams();
params.set('student_id' , 'some_id');
params.set('password' , 'some_password');
let studentInfo = await fetchStudentInfo(params);
return res.json(studentInfo);
} catch (err) {
next(err);
}
});
获取数据的函数:
function fetchFacultyInfo(params) {
let url = "https://somesiteasdasdadsa.com?";
return fetch(url + params)
.then(result => result.json())
.then(jsonData => {
return jsonData;
})
.catch(e => {
return e;
});
}
当您有一个被拒绝的 Promise 并对其调用.catch
时,除非catch
某些内容抛出,否则它将返回一个已解决的Promise。 由于您在这里.catch
ing, fetchFacultyInfo
函数将返回一个始终解析的 Promise。
通常仅在您实际上能够以某种方式处理错误时才捕获错误也是一个好主意 - 否则,只需让错误渗透到调用堆栈中,直到可以处理它的错误处理程序看到它:
function fetchFacultyInfo(params) {
let url = "https://somesiteasdasdadsa.com?";
return fetch(url + params)
.then(result => result.json())
}
这样,如果fetch
或json()
拒绝,则await fetchStudentInfo(params);
将失败,并将控制流发送到调用next
的catch
块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.