异步迭代器报意外token“*”错误,TS类异步生成器问题求助
解决TypeScript异步生成器中“意外token‘*’”的错误
你遇到的问题主要来自两个核心点:异步生成器内部的this指向丢失,以及错误地直接yieldmap返回的异步生成器数组,这两个问题叠加可能触发语法解析器抛出“意外token”的错误。下面一步步帮你修复:
问题拆解
this指向混乱:你在map回调里用了普通的async function*(channel),这个函数的this不会绑定到你的类实例,而是会指向map的调用上下文,这不仅会导致this.compileTemplate这类类方法调用失败,还会让TypeScript的语法解析器出现混淆,触发token错误。- 无效的yield操作:
this._channels.map(...)返回的是一个装满异步生成器对象的数组,直接yield这个数组是不符合异步生成器语法的,你需要委托迭代每个生成器的结果。
具体解决方案
1. 修复this指向
把map里的普通异步生成器函数改成箭头函数,箭头函数会自动继承外层的this(也就是你的类实例):
// 错误写法 this._channels.map(async function*(channel) { ... }) // 正确写法 this._channels.map(async*(channel) => { ... })
2. 正确委托生成器结果
不要直接yield数组,推荐用for...of遍历通道逐个处理,这种写法更清晰,也避免了数组嵌套迭代的问题:
public async *iterator() { let output: IDictionary = {}; const substitutions = this.isListDataset ? this._substitutions : [this._substitutions]; // 遍历每个通道,逐个处理并yield结果 for (const channel of this._channels) { const fn = await this.compileTemplate(this._topic, channel); const channelOutput: ITemplateChannel = { channel, templates: [] }; // 处理每个substitution(根据你的业务逻辑调整) for (const sub of substitutions) { const templateResult = await fn(sub); channelOutput.templates.push(templateResult); } // yield当前通道的最终结果 yield channelOutput; } }
3. 确保TypeScript配置支持异步生成器
检查你的tsconfig.json,确保启用了对应版本的语法支持:
{ "compilerOptions": { "target": "ES2018" /* ES2018及以上版本原生支持异步生成器 */, "lib": ["ES2018", "DOM"], "downlevelIteration": true /* 如果需要兼容低版本浏览器/Node.js环境 */ } }
完整修正后的代码示例
/** * 提供一种逐个通道遍历模板的方式。 */ public async *iterator() { let output: IDictionary = {}; const substitutions = this.isListDataset ? this._substitutions : [this._substitutions]; for (const channel of this._channels) { // 直接使用类实例的compileTemplate,this指向正确 const fn = await this.compileTemplate(this._topic, channel); const channelOutput: ITemplateChannel = { channel, templates: [] }; // 遍历substitutions生成模板内容 for (const sub of substitutions) { const templateContent = await fn(sub); channelOutput.templates.push(templateContent); } // 逐个yield每个通道的处理结果 yield channelOutput; } }
这样修改后,既解决了this指向的问题,也修正了异步生成器的迭代逻辑,应该能彻底消除“意外token‘*’”的错误。
内容的提问来源于stack exchange,提问作者ken
相关产品推荐
相关产品推荐

