使用some 或者 every 方法遇到异常没有return

使用some 或者 every 方法遇到异常没有return

解决方法

使用for循环或者for of遍历

for (const file of filesArray) {
   
        try {
   
            formatBytes(file.size);
        } catch (e: any) {
   
            setErrorMessage(e.message);
            return;
        }
    }

问题复现

写了一个方法(formatBytes)将文件的大小自动转换成MBKB等,如果其中文件大小超过指定大小会抛出异常。想法是在遍历文件列表时如果超过指定大小,给出提示并且直接return

formatBytes方法

import {
    maxFileSize } from '@/config/fileType';

export function formatBytes(bytes: number, decimals = 2) {
   
    const size = maxFileSize * 1024 * 1024;
    if (bytes > size) {
   
       throw new Error(`文件不能超过${
     maxFileSize}M`);
    }

    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return `${
     parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${
     sizes[i]}`;
}

然而,在实际使用中,无论是使用someforEach还是every方法,都会在最后设上值。在遇到异常时,这几个方法并没有立即返回。

代码如下

// 文件改变时
const handelFilesChange = (event: any) => {
   
    const filesArray: File[] = Array.from(event.target.files);

    filesArray.forEach(file => {
   
        try {
   
            formatBytes(file.size);
        } catch (e: any) {
   
            setErrorMessage(e.message);

            return;
        }
    });

    const map = filesArray.map(file => ({
    id: uuid(), file }));
    setFiles(map);
};

通过使用普通的for循环或for...of遍历,可以在捕获到异常时直接设置错误消息并立即返回,避免在异常情况下继续执行不必要的代码。

最近更新

  1. TCP协议是安全的吗?

    2024-01-01 09:54:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-01 09:54:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-01 09:54:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-01 09:54:02       20 阅读

热门阅读

  1. 全连接层:神经网络的桥梁

    2024-01-01 09:54:02       44 阅读
  2. Excel数据写入Word 轻松套打通知书、证书、票据等

    2024-01-01 09:54:02       41 阅读
  3. udp进行数据发送与接收

    2024-01-01 09:54:02       35 阅读
  4. 【springboot 事件发布机制源码浅析】

    2024-01-01 09:54:02       38 阅读
  5. 10-2 HNCST - 多线程4 - 线程同步Condition——python

    2024-01-01 09:54:02       38 阅读
  6. ajax 下载文件(excel导出)

    2024-01-01 09:54:02       41 阅读
  7. vue怎么跨页面传参

    2024-01-01 09:54:02       44 阅读
  8. 纯前端 文件预览方法汇总

    2024-01-01 09:54:02       46 阅读