【问题标题】:Chrome debugger - parameters in async functions called from templateChrome 调试器 - 从模板调用的异步函数中的参数
【发布时间】:2018-07-27 12:07:01
【问题描述】:

我的角度模板我使用以下组件:

 <building-selection 
     (done)="sendToBackend($event)"
     >
 </building-selection>

这个组件向用户显示带有复选框的建筑物图像,当他完成检查时,它会发出带有所选建筑物的数组的事件

在打字稿代码中,以下功能起作用:

public async sendToBackend(buildings) 
{
    console.log({buildings}); 
    debugger; // I see buildings "debugger variable preview"
    ... 
}

但如果我注释掉 console.log 然后在“调试器变量 预览”我看到消息(如果我们有非异步功能则不会出现这种现象):

ReferenceError:建筑物未在 eval 处定义(eval at (http://project.localhost:3003/main.bundle.js:53596:17), :1:1) 在 ClientProjectEditorComponent。

...调用任务 (http://project.localhost:3003/polyfills.bundle.js:14037:14)↵ 在 HTMLUnknownElement.globalZoneAwareCallback (http://project.localhost:3003/polyfills.bundle.js:14063:17)" 原型 : 错误

问题:当console 语句被注释掉时,为什么debugger 关键字的作用不同?

【问题讨论】:

    标签: google-chrome typescript async-await javascript-debugger


    【解决方案1】:

    问题在于async 函数将被转换为生成器函数,该生成器函数将在您每次await 时进行迭代。例如:

    public async sendToBackend(buildings) 
    {
        await sleep();
        debugger; 
        await sleep();
    }
    // Generated js for target es2015
    
    sendToBackend(buildings) {
        return __awaiter(this, void 0, void 0, function* () {
            yield sleep();
            debugger; 
            yield sleep();
        });
    }
    

    如您所见,您的实际函数的代码最终将成为一个匿名函数,该函数将传递给__awaiter 辅助函数。参数列表仍然存在于原始函数中,并且匿名函数可以访问参数,但是如果匿名函数没有通过在其主体中引用它们来捕获参数,那么调试器将无法检查它们。当您添加 console.log 时,匿名函数会引用该参数,因此它将被捕获,因此可以在手表中进行检查。

    上面的代码是为 es2015 编译的,es5 的讨论类似,但生成的代码更难理解,因为生成器也必须模拟。

    【讨论】:

      猜你喜欢
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-22
      • 2020-09-29
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      相关资源
      最近更新 更多