[英]Try/catch block breaks asynchronous JS code
我有以下數據庫調用
const x = await doThis();
cons y = await doThat(x);
return somethingElse(x,y)
這可以正常工作,但是當沒有正確返回承諾時,將無法進行調試。 我想寫類似下面的代碼
try {
const x = await doThis();
} catch (e) {
console.log(e);
}
try {
cons y = await doThat(x);
} catch (e) {
console.log(e);
}
return somethingElse(x,y);
但是,出現以下錯誤:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: x is not defined
try / catch塊會阻止代碼異步運行嗎? 我該如何解決?
當用let
或const
聲明變量時,它們在括號內 。
在您的代碼中, x
和y
放在括號內的try
語句中-為什么不在try
之外定義它們。 您需要在try
語句之前定義它們。
您也可以將const
替換為var
。 這將在函數的開始處懸掛變量聲明(基於它是函數的return
語句)並且可以工作x
和y
對整個函數可見,但是我建議對let
聲明使用該方法。
let x, y;
try {
x = await doThis();
} catch (e) {
console.log(e);
}
try {
y = await doThat(x);
} catch (e) {
console.log(e);
}
return somethingElse(x,y);
它與范圍界定有關。 您可以在try塊內聲明x和y,以便它們僅在該塊內作用域。 在塊外聲明它們,並在try塊內分配值。 請記住,如果存在異常,則值仍可能是不確定的,在這種情況下,應在繼續下一個調用之前檢查值。
let x, y;
try {
x = await doThis();
} catch (e) {
console.log(e);
}
try {
if(x) // check if x has a value, if there was an exception then x could be undefined
y = await doThat(x);
} catch (e) {
console.log(e);
}
if(y) // check if y has a value, if there was an exception then y could be undefined
return somethingElse(x,y);
return null;// or something else??
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.