2016-10-25 49 views
0

我想在AWS Lambda上运行Nightmare JS,但是我的函数总是返回null,并且似乎没有运行任何异步代码。这里是我的代码:AWS上的承诺Lambda函数不解决/返回 - Nightmare JS

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,虽然这个过程应该至少需要几秒钟,该功能一般在100毫秒左右结束。前两个控制台日志(大于return nightmare.goto...)由Lambda注册,但后来的日志不是。

有什么我做错了吗?

+0

context.success不是一个nodejs函数,你的意思是context.succeed? –

+0

也值得一提;一旦你调用context.succeed,该方法将返回并且后续行将不会被执行。 –

+0

好的,谢谢你。是的,我的意思是背景成功。但是,似乎lambda甚至没有越过'return nightmare.goto(...)',所以我不确定这是导致问题的原因。 – otajor

回答

0

这是不工作的原因是,梦魇需要各种网络驱动程序才能运行,这是不存在的Lambda,并据我所知不能安装。

当我将函数代码上传到Lambda时,我绑定了我的node_modules,但这还不够。

有一个long thread on the Nightmare repo here讨论如何在Linux上无恶意地运行Nightmare,但这需要您通过apt-get安装各种依赖关系,据我所知在Lambda上是不可能的。

如果您在未来找到方法,请确保留下一个答案!

0

我想你只看到一条日志语句的主要原因是exists的计算结果为false(或者JavaScript认为是假的任何其他值)。我基于这样的假设:else执行路径由简单的return语句组成,而不是使用lambda callback函数(或者如果使用旧版本,则为context.succeedcontext.fail)。不执行callback可能导致Lambda函数在完成(或写入日志)之前终止。

要在实践中验证这一点,请更改最后一个return语句

callback(null, 'not present`) 

,表明LAMBDA执行成功,或

​​

,如果你认为这是一个lambda错误。

也请考虑到成功结果的then部分更新到像

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

欲了解更多信息,请阅读AWS文档的Using the Callback Parameter款lambda函数处理程序的。

+0

你说得对,我错误地使用了回调。但是,我不认为你的解释是正确的 - 我也没有看到'if(exists){..}'上面的行上的console.log(),它应该在所有情况下运行。 似乎有一个噩梦承诺链没有记录或投入Lambda环境的问题。 – otajor

+0

刚刚做出了您所建议的更改,但没有帮助 - 仍然返回null。 – otajor