利用批量文件打印解释JS关于异步加载async()方法的梳理

首先引入几个js的概念:

1.async()和then()
.async() 和 .then() 是 JavaScript 中用于处理异步操作的重要方法。
①、async/await:
async 和 await 是 ES2017(ES8)引入的异步编程的新特性,使得处理异步代码更加直观和易读。以下是它们的详细说明:
async 函数用于定义一个返回 Promise 对象的异步函数。异步函数会自动将返回值封装成一个 Promise 对象。

async function myAsyncFunction() {
  return 42;
}

// 调用 async 函数会返回一个 Promise
myAsyncFunction().then(result => {
  console.log(result); // 输出 42
});

await 关键字:
await 关键字只能在 async 函数中使用,它用于等待一个 Promise 对象的解决或拒绝。它会暂停当前 async 函数的执行,直到 Promise 完成。

async function getData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}

getData().then(data => {
  console.log(data);
});

②、Promise 和 .then():
Promise 是一种用于处理异步操作的内建对象,它代表一个异步操作的最终完成或失败。

const myPromise = new Promise((resolve, reject) => {
  if (/* 异步操作成功 */) {
    resolve('成功的结果');
  } else {
    reject('失败的原因');
  }
});

myPromise.then(
  result => {
    console.log(result); // 如果成功,输出 '成功的结果'
  },
  error => {
    console.error(error); // 如果失败,输出 '失败的原因'
  }
);

.then() 方法:
.then() 方法是 Promise 对象提供的用于注册在 Promise 完成时的回调函数。它接收两个参数,第一个是在 Promise 完成时调用的函数,第二个是在 Promise 失败时调用的函数。

myPromise.then(
  result => {
    console.log(result); // 如果成功,输出 '成功的结果'
  },
  error => {
    console.error(error); // 如果失败,输出 '失败的原因'
  }
);

区别与联系:
async/await 是用于处理异步代码的语法糖,使得异步代码看起来像同步代码,而 Promise 是一种更底层的异步编程模型。
async/await 基于 Promise,可以理解为是 Promise 的一个更高级的封装和使用方式。
async/await 可以使异步代码的流程更加清晰、直观,尤其在处理多个异步操作的情况下。
2、map()
map() 是 JavaScript 中数组的一个高阶函数,用于对数组中的每个元素进行操作,并返回一个新的数组,其中包含对每个元素应用函数后的结果。下面是关于 map() 的详细说明:

const newArray = array.map(callback(currentValue[, index[, array]])[, thisArg]);

array: 要操作的原始数组。
callback: 用于处理每个元素的函数。
currentValue: 当前处理的元素的值。
index (可选): 当前处理的元素的索引。
array (可选): 原始数组。
thisArg (可选): 在 callback 函数中使用的 this 值。
返回值
map() 返回一个新数组,其中包含了对原始数组中每个元素应用 callback 后的结果。

使用示例

  1. 简单的示例:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function (num) {
  return num * 2;
});

// doubledNumbers 现在包含 [2, 4, 6, 8, 10]

  1. 使用箭头函数:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(num => num * 2);

  1. 使用回调函数处理对象数组:
const students = [
  { name: 'Alice', score: 85 },
  { name: 'Bob', score: 92 },
  { name: 'Charlie', score: 78 }
];

const adjustedScores = students.map(student => ({
  name: student.name,
  adjustedScore: student.score + 5
}));

/*
adjustedScores 现在包含:
[
  { name: 'Alice', adjustedScore: 90 },
  { name: 'Bob', adjustedScore: 97 },
  { name: 'Charlie', adjustedScore: 83 }
]
*/

注意事项
map() 不会改变原始数组,而是返回一个新的数组。
callback 函数应该是无副作用的,即不应该修改原始数组或其他外部状态。
在处理异步操作时,map() 可以与 async/await 结合使用。

实战案例:

本文根据个人实战案例来阐述在使用上述技术中遇到的问题:
案例主要是将后台获取到的压缩文件进行解压获取内部图片文件并将其进行转化为imgurl进行打印,具体代码如下:

//批量标签打印
function doMutilPrint(mark) {

    xhr.open('GET', "访问api", true);
    xhr.responseType = 'arraybuffer';// 指定响应类型为二进制数据流

    xhr.onload = function () {
        if (xhr.status === 200) {
            var blob = xhr.response;
            // 继续下一步操作(将Blob转换为文件)
            var file = new File([blob], 'mutillabel.zip', {type: 'application/zip'});
            console.log("file:" + file);

            if (file) {
                // 使用JSZip库来解压缩.zip文件
                var jszip = new JSZip();
                jszip.loadAsync(file)
                    .then(function (zip) {
                        // 获取压缩文件中的所有文件列表
                        var fileList = [];
                        var imageURLs=[];
                        zip.forEach(function (relativePath, zipEntry) {
                            if (!zipEntry.dir && isImageFile(zipEntry.name)) { // 检查是否为图片文件
                                fileList.push(zipEntry);
                            }
                        });
                        // 在所有条目都读取完成后执行进一步的操作
                        Promise.all(fileList.map(function (zipEntry) {
                            return zipEntry.async('blob').then(function (imageBlob) {//将zipEntry转换为blob类型
                                var imageURL = URL.createObjectURL(imageBlob);
                                imageURLs.push(imageURL);
                            }).catch(function (error) {
                                console.error('转换为Blob对象时出错:', error);
                            });
                        })).then(function () {
                            // 所有异步操作完成后执行此处的代码
                            // imageURLs 数组现在包含所有生成的imageURL
                            // 在这里执行打印操作或其他相关操作
                            jsprintImage(imageURLs);
                        }).catch(function (error) {
                            console.error('处理图像时出错:', error);
                        });
                    })
                    .catch(function (error) {
                        console.error('解析.zip文件时出错:', error);
                    });
            } else {
                console.error('后台请求所错,返回响应状态码:', xhr.status);
            }
        }
    };
    xhr.send();
}

本文利用jszip库来将后台获取的文件进行解压,通过zipEntry异步加载压缩文件中的图片内容,最后将内容进行打印,在编写过程中,因为zipEntry.async(‘blob’).then()的异步加载问题,使得在处理先转化图片文件后打印的顺序产生错误,,最后通过实践,将获取的图片文件在promise.all中进行imgurl转化即可按照逻辑顺序进行打印,即

Promise.all(fileList.map(function (zipEntry) {}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值