将回调传递给事件处理程序

Passing a callback to an event handler

我正在 AWS Lambda 中运行的 Node 中研究 Alexa 技能,但在发出事件时无法执行回调。 Node.JS 自述文件的 Alexa-skills-kit 演示了将回调函数传递给事件处理程序,并建议使用箭头函数来保留上下文:

    this.emit('JustRight', () => {
        this.emit(':ask', guessNum.toString() + 'is correct! Would you like to play a new game?',
        'Say yes to start a new game, or no to end the game.');
    });

我正在尝试做同样的事情,但发现我的回调似乎从未执行过。我认为这是因为 AWS Lambda 仅限于 Node 4.3.2,箭头函数不可用,所以我尝试以老式的方式将此上下文传递回回调:

在新会话处理程序中:

if(!account_id) {
    console.log('Access token:' + accessToken);
    this.emit('getAccount', accessToken, function (retrieved_id) {
        console.log('account id in callback: ' + retrieved_id);
        this.emit('welcome');
    });
}

在事件处理程序中:

accountHandler = {
    'getAccount': function (accessToken, cb) {
        console.log('fetching account id');
        var client = thirdparty.getClient(accessToken);
        var r = client.getAccountForToken(client);
        r.then(function (data) {
            console.log('got it:' + data);
            this.attributes['account_id'] = data;
            cb.call(this, data);
        }).catch(function (err) {
            this.emit('handleApiError', err);
        });
    },
}

我可以看到我在日志中成功检索了帐户 ID,但 Lambda 执行时没有错误,也没有调用我的回调函数。我试图弄清楚在 Promise 'then' 函数中调用回调是否存在问题,或者是否发生了其他问题。

确切的问题是在 promise then 函数中缺少上下文。我通过使用 getAccount 处理程序中的箭头函数解决了这个问题:

r.then(data => {
    console.log('got it:' + data);
    this.attributes['account_id'] = data;
    this.emit('welcome');
})

当然这也说明Lambda Node.JS函数支持箭头函数就好了