AWS Lambda函数的承诺无法解析/返回 - Nightmare JS

时间:2016-10-25 21:58:22

标签: amazon-web-services aws-lambda nightmare

我正在尝试在AWS Lambda上运行Nightmare JS,但我的函数总是返回null并且似乎没有运行任何异步代码。这是我的代码:

exports.handler = (event, context, callback) => {
  console.log('starting....')
  const Nightmare = require('nightmare')
  const nightmare = Nightmare()
  console.log('created Nightmare: ', nightmare)
  return nightmare
    .goto('https://www.myurl.com')
    .exists('[data-selector-element]')
    .then((exists) => {
      console.log('element exists: ', exists)
      if (exists) {
        return nightmare.click('[data-selector-element]')
          .wait(200)
          .evaluate(() => {
            const title = document.querySelector('h1.header')
            return { title }
          })
          .then((res) => {
            context.success(res)
            console.log('success:', res)
            callback('success: ')
            return res
          })
      } else {
        return 'not present'
      }
    })
}

该函数始终返回null,虽然此过程至少需要几秒钟,但该函数通常以大约100ms结束。前两个控制台日志(在return nightmare.goto...之上)由Lambda注册,但后来的日志不是。

我有什么问题吗?

2 个答案:

答案 0 :(得分:0)

我猜你只看到一个日志语句的主要原因是exists评估为false(或者JavaScript认为是假的任何其他值)。我的假设基于以下事实:执行的else路径包含一个简单的return语句,而不是使用Lambda callback函数(或context.succeedcontext.fail如果你使用旧版本)。不执行callback可能导致Lambda函数在完成(或写入日志)之前终止。

要在实践中验证这一点,请将最后一个返回语句更改为

callback(null, 'not present`)

表示Lambda执行成功,或

callback('not present`)

如果您认为这是Lambda错误。

还请考虑将成功结果的then部分更新为

.then((res) => {
    console.log('success:', res)
    callback(null, 'success: ')
})

有关详细信息,请阅读AWS文档中Lambda函数处理程序的Using the Callback Parameter段。

答案 1 :(得分:0)

这不起作用的原因是Nightmare需要各种网络驱动程序才能运行,Lambda上没有这些驱动程序,据我所知,无法安装。

当我将我的功能代码上传到Lambda时,我正在捆绑我的node_modules,但这还不够。

sa long thread on the Nightmare repo here讨论如何在Linux上无头地运行梦魇,但这要求您通过apt-get安装各种依赖项,据我所知,这不是可能在Lambda上。

如果您将来找到方法,请留下答案!

相关问题