WebTorrent报错TypeError:无法读取undefined的find属性求助
问题解决:WebTorrent流式播放中
Cannot read properties of undefined (reading 'find') 你的错误根源很明确——existingTorrent打印为Promise { <pending> },说明你直接在未解析的Promise对象上访问files属性了。Promise本身没有files属性,只有当Promise完成(resolve)后得到的真实torrent对象才会包含该属性。
具体解决步骤:
处理异步Promise,等待torrent对象解析
WebTorrent的client.add()(或类似获取torrent的方法)返回的是Promise,必须用await或.then()等待它完成,才能拿到可用的torrent对象。
错误示例:const existingTorrent = client.add(magnetUri); const file = existingTorrent.files.find(...) // 此处existingTorrent是Promise,不是实际torrent对象正确写法(async/await):
// 确保所在函数为async类型 async function handleStream(magnetUri) { try { const torrent = await client.add(magnetUri); // 可选但推荐:等待torrent元数据加载完成,确保files列表就绪 await new Promise(resolve => torrent.on('metadata', resolve)); const file = torrent.files.find(file => file.name.endsWith('.mp4')); // 后续流式播放逻辑处理 } catch (err) { console.error('Error handling stream:', err); } }也可以用
.then()链式调用:function handleStream(magnetUri) { client.add(magnetUri) .then(torrent => { torrent.on('metadata', () => { const file = torrent.files.find(file => file.name.endsWith('.mp4')); // 执行播放处理 }); }) .catch(err => console.error('Error handling stream:', err)); }兼容文件后缀大小写
部分种子内的MP4文件可能使用大写后缀(.MP4),可将判断逻辑改为兼容大小写:const file = torrent.files.find(file => file.name.toLowerCase().endsWith('.mp4'));后端接口的异步处理
确保后端streamMovie接口调用handleStream时正确处理异步逻辑——如果handleStream是async函数,需添加await,避免Promise未解析就返回结果。
内容的提问来源于stack exchange,提问作者arlaine
相关产品推荐
相关产品推荐

