簡體   English   中英

Javascript 在 try 塊內設置 const 變量

[英]Javascript set const variable inside of a try block

ES6中是否可以在嚴格模式下使用consttry{}中設置變量?

'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);

或者,雖然可能更令人困惑,但您可以使用vartry創建一個變量並在它之外使用它,因為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));
}

學習自: https : //stackoverflow.com/a/55024396/2936521

你可以這樣做:


  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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM