[英]Javascript set const variable inside of a try block
在ES6中是否可以在嚴格模式下使用const
在try{}
中設置變量?
'use strict';
const path = require('path');
try {
const configPath = path.resolve(process.cwd(), config);
} catch(error) {
//.....
}
console.log(configPath);
這無法檢查,因為configPath
是在 scope 之外定義的。這似乎唯一可行的方法是:
'use strict';
const path = require('path');
let configPath;
try {
configPath = path.resolve(process.cwd(), config);
} catch(error) {
//.....
}
console.log(configPath);
基本上,對於這種情況,有什么方法可以使用const
而不是let
嗎?
將變量聲明為const
要求您立即將其指向一個值,並且此引用無法更改。
這意味着你不能在一個地方(外定義它try
)和其他(內部的某個地方給它分配一個值try
)。
const test; // Syntax Error try { test = 5; } catch(err) {}
另一方面,在try
塊中創建它並給它一個值都很好。
try { const test = 5; // this is fine } catch(err) {}
然而, const
是塊范圍的,就像let
一樣,所以如果你創建它並在你的try
塊中給它一個值,它只會存在於那個范圍內。
try { const test = 5; // this is fine } catch(err) {} console.log(test); // test doesn't exist here
因此,如果您需要在try
之外訪問此變量,則必須使用let
:
let configPath;
try {
configPath = path.resolve(process.cwd(), config);
} catch(error) {
//.....
}
console.log(configPath);
或者,雖然可能更令人困惑,但您可以使用var
在try
創建一個變量並在它之外使用它,因為var
范圍在函數內,而不是塊內(並被提升):
try {
var configPath = path.resolve(process.cwd(), config);
} catch(error) {
//.....
}
console.log(configPath);
'use strict';
const path = require('path');
const configPath = (function() {
try {
return path.resolve(process.cwd(), config);
} catch (error) {
//.....
}
})()
console.log(configPath);
我會嘗試將臨時變量與let
一起使用,並在try
/ catch
和“刪除”臨時變量之后將其分配給const
var。
'use strict';
let temp;
try {
temp = path.resolve(process.cwd(), config);
} catch (error) {
//.....
}
const configPath = temp;
temp = undefined;
console.log(configPath);
這里有很多很好的答案。 但是必須管理您的允許在范圍內和范圍外確實很煩人。 所以如果你和我一樣,來到這里尋找更好的模式。 我寫了一個小實用程序,可以幫助很多。
export const tc = <T>(option: { try: () => T; catch: (e: Error) => T }) => {
try {
return option.try()
} catch (e) {
return option.catch(e)
}
}
這里有一些單元測試來展示它是如何有用的
import { tc } from './tc'
describe('tc', () => {
it('should return successfully', () => {
const result = tc({
try: () => 1 + 2,
catch: () => -1,
})
expect(result).toEqual(3)
})
it('should catch', () => {
const spy = jest.fn()
const result = tc({
try: (): number => {
throw new Error('Test')
},
catch: (e) => {
spy()
expect(e.message).toEqual('Test')
return -1
},
})
expect(spy).toHaveBeenCalledTimes(1)
expect(result)
})
it('should rethrow', () => {
expect(() =>
tc({
try: (): number => {
throw new Error('Test')
},
catch: (e) => {
throw e
},
}),
).toThrowError()
})
it('should have proper types', () => {
// @ts-expect-error
const result: string = tc({
try: () => 12,
catch: (e) => {
return -1
},
})
})
})
除了我在這里看到的let
選項之外,另一個選項可能是使用對象,因為對對象的引用是常量,但它的屬性可以改變,所以像這樣:
'use strict';
const path = require('path');
const configPath = { value: null };
try {
configPath.value = path.resolve(process.cwd(), config);
} catch(error) {
//.....
}
console.log(configPath.value);
堅持使用 let 可能會更清晰,但我只是想指出另一種可能的選擇。
如果函數是異步的,你可以完全避免 try 塊! 今天剛學會這個,我想我會分享!
更廣泛地適用於您的情況,因為這是“const in a try block”的最佳 Google 結果
use strict';
const path = require('path');
const getPath = async () => {
return path.resolve(process.cwd())
}
const logPath = async () => {
const configPath = await getPath().catch(e => console.log(e)) <--avoid the try
console.log(configPath);
}
logPath()
當您已經在異步函數中並且需要等待其他事情時,效果很好:
async function main() {
const result = await asyncTask().catch(error => console.error(error));
}
你可以這樣做:
const result = await promise.catch(err=>{
console.log(err)
})
使用let
。 您不能使用const
。 const
不允許您重新分配聲明的常量。 雖然使用const
聲明像您這樣的對象通常是一種很好的做法,但這樣做的全部意義在於允許對象發生變異而不允許重新分配它們。 您正在重新分配對象(因此,違背了const
的目的),因此請改用let
。
let path = require('path');
// Good to go!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.