2017-06-17 51 views
0

我对AWS lambda和node.js都是新手。我已经通过一些异步架构进行了摔角,这些架构让我很熟悉,但仍然没有经验,还有回调。我确定这是相关的,但我不明白为什么,因为如果我在本地测试它,它会运行得很好。我已经正确设置了环境变量并测试了它也被传递了。AWS Lambda和Node.js函数没有被调用

在下面的代码片段中,我使用Claudia Bot Builder来获取一条slack-slash-command消息,并将它传递给此SlackResponse函数,该函数使用Node Hubspot API通过用户名进行查询。出于某种原因,client.contacts搜索命令从不被调用。所有console.log()报告都显示出来,但搜索回调似乎从不会执行,甚至是异步执行。

function SlackResponse(message, request, debug, currentresponse){ 
var SlackResponse = currentresponse; 
var SenderID = message.originalRequest.user_name; 
var CustomerID = 0; 

if (debug){ 
    SlackResponse += 'Slack Debug On' + '\r'; 
    SlackResponse += 'SenderID: ' + SenderID + '\r'; 
} 
client.useKey(process.env.HAPI_Key); 
console.log('API Key set \r'); 
console.log(message); 
console.log(currentresponse); 

client.contacts.search(SenderID, 
    function processSearchResult(err, res) { 
     console.log('In processSearchResult function \r'); 
     console.log(JSON.stringify(res)); 
     if (err) { console.log('uh oh'); throw err; } 
     if (res.total === 0) 
     { 
      if(debug){console.log('New Customer Identified' + '\r')} 

      // Create a new Contact 
      var payload = { 
       "properties": [ 
        { 
         "property": "firstname", 
         "value": SenderID 
        }] 
      } 
      client.contacts.create(payload, function(err, res){ 
       if (err) { throw err; } 
       CustomerID = res.vid; 
       if(debug){console.log('New Customer Created with CustomerID: ' + CustomerID + '\r')} 
      }) 
     } 
     else 
     { 
      CustomerID = res.contacts[0].vid; 
      if(debug){console.log('Hubspot CustomerID:' + CustomerID + '\r')} 
     } 

     } 
); 
console.log('About to return \r'); 
return SlackResponse; 

}

任何人都可以解释为什么这是发生?这是一个权限问题?为什么它在本地运行,但不在AWS中运行?

+0

当函数执行完毕什么被记录在日志的CloudWatch?是否有错误讯息?该功能是否超时?什么是函数的配置超时值?您是否将此功能配置为在没有NAT网关的情况下在VPC内部运行? –

+0

CloudWatch按预期方式显示记录到client.contacts.search()调用。没有错误信息,我可以看到,虽然有可能我没有在这里找一个合适的菜鸟。函数使用默认的超时值,我相信这在Claudia中默认为两分钟。我不知道如何回答你最后的问题,因为我不知道这意味着什么。 – dave

+0

应该有一个日志行说明函数执行的时间,以及它是否正常退出,或者有错误或超时。 –

回答

0

这看起来像是一个JavaScript承诺问题。

Claudia API和Bot Builders使用JavaScript承诺来处理异步操作。如果你在本地运行这个例子,它将起作用,因为你的函数将被执行,但是如果你在Lambda函数client.contacts.search(SenderID,上运行它,将会中止承诺链,并且Lambda函数将被关闭,这意味着没有别的东西会被执行。

要解决这个问题,您需要将异步操作封装到JavaScript承诺中,如果它们不支持它们的话。例如:

setTimeout(function() { 
    return 'Hello' 
}, 1000) 

应该改为:

return Promise(function(resolve, reject) { 
    setTimeout(function() { 
    resolve('Hello') 
    }, 1000) 
}) 

或者,在你的榜样:

return new Promise(function(resolve, reject) { 
    client.contacts.search(SenderID, function (err, res) { 
    if (err) { 
     return reject(err) 
    } 

    // Do your logic 
    resolve(finalResult) 
    } 
}