在 NodeJs 專案中,我以這種方式呼叫我的異步函式:
const response = await myFunction();
這是函式的定義:
myFunction = async () => {
return await new Promise((next, fail) => {
// ...
axios({
method: 'get',
url: apiEndpoint,
data: payload
}).then(function (response) {
// ...
next(orderId);
}).catch(function (error) {
fail(error);
});
});
}
如果發生這種情況,我應該如何正確攔截錯誤?即當我等待函式時我如何管理它?
uj5u.com熱心網友回復:
您可以使用塊來實作和簡化它try-catch,具體取決于您要如何處理錯誤
async function myFunction () {
try {
const response = await axios({
method: 'get',
url: apiEndpoint,
data: payload
})
// ... do something with response
} catch (error) {
// ... do something with error
}
}
但是如果你想在你的函式中鏈接承諾,你可以直接回傳axios呼叫
function myFunction () {
return axios({ method: 'get', url: apiEndpoint, data: payload })
}
// ...
myFunction().catch(e => {
// ... do something with the error
})
uj5u.com熱心網友回復:
使用嘗試/捕獲:
let response;
try {
response = await myFunction();
} catch (error) {
// Handle error here.
}
uj5u.com熱心網友回復:
你可以做
try {
const response = await axios({
method: 'get',
url: apiEndpoint,
data: payload
})
next(orderId);
} catch (error) {
fail(error)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/496684.html
標籤:javascript 节点.js 异步等待 承诺
下一篇:陣列陣列的打字稿陣列:防止未定義
