如何将元数据与Promise绑定,通过Promise.all同步获取结果与元数据?
解决Promise与元数据绑定的问题
当然可以实现,核心思路是让每个Promise最终解析为包含请求结果和对应元数据的对象,这样Promise.all返回的数组里每个元素都能同时拿到两者,不用再靠索引匹配。
方法1:修改异步函数直接返回带元数据的对象
给你的异步函数添加元数据参数,执行完成后返回包含结果和元数据的对象:
function loadStuff(value, delay) { return new Promise((resolve) => setTimeout(() => resolve(value), delay)); } async function loadStuffandEnhance(value, delay, meta) { let result = await loadStuff(value, delay); result += '__enhanced'; // 返回包含结果和元数据的对象 return { result, meta }; } function test() { let loader_promises = []; for (let i = 0; i < 20; i++) { // 定义当前请求的元数据 const itemMeta = { fileType: i % 2 === 0 ? 'image' : 'text', targetPath: `/assets/${i}`, id: i }; loader_promises.push( loadStuffandEnhance(`item${i}`, Math.random() * 1000 + 100, itemMeta) ); } Promise.all(loader_promises).then((loaded_things) => { loaded_things.forEach(({ result, meta }) => { console.log('处理结果:', result); console.log('对应元数据:', meta); }); }); } test();
方法2:不修改原函数,用Promise.then包装结果
如果不想改动原有的异步函数,可以在推入Promise数组时,通过.then把结果和元数据组装成对象:
function loadStuff(value, delay) { return new Promise((resolve) => setTimeout(() => resolve(value), delay)); } async function loadStuffandEnhance(value, delay) { let result = await loadStuff(value, delay); result += '__enhanced'; return result; } function test() { let loader_promises = []; for (let i = 0; i < 20; i++) { const itemMeta = { fileType: i % 2 === 0 ? 'image' : 'text', targetPath: `/assets/${i}`, id: i }; // 用then包装原Promise的结果,绑定元数据 const wrappedPromise = loadStuffandEnhance(`item${i}`, Math.random() * 1000 + 100) .then(result => ({ result, meta: itemMeta })); loader_promises.push(wrappedPromise); } Promise.all(loader_promises).then((loaded_things) => { loaded_things.forEach(({ result, meta }) => { console.log('处理结果:', result); console.log('对应元数据:', meta); }); }); } test();
这两种方式都能让你在Promise.all解析后,直接从每个结果元素中获取对应的元数据,彻底摆脱索引匹配的麻烦。
内容的提问来源于stack exchange,提问作者Molly Birk
相关产品推荐
相关产品推荐

