【问题标题】:Lambda node "hello undefined" async/await don't work?Lambda 节点“hello undefined”异步/等待不起作用?
【发布时间】:2020-06-11 07:57:23
【问题描述】:

这是我的问题:我想在我的 aws-lambda 函数 (nodejs 12) 中调用 Vimeo api 来获取有关视频的一些信息/数据(例如:持续时间、标题……)。

这是我的代码:

exports.handler = async event => {
  let Vimeo = require("vimeo").Vimeo;
  let client = new Vimeo("{client_id}", "{client_secret}", "{access_token}");
  console.log('client => ',

 client);
  console.log('event => ', event);
  video_id = event.video_id;
  const res = await client.request(
    {
      method: "GET",
      path: `/users/1234567890/videos/${video_id}`
    },
    function(error, body, status_code, headers) {
      if (error) {
        console.log("error", error);
      }
      console.log("body", body);
      console.log("status code");
      console.log(status_code);
      console.log("headers");

      console.log(headers);
      return body;
    }
  )
  console.log('hello', res);
  return 'ok';
};

为了尝试它,我启动了一些测试。 lambda 返回ok,所以我知道我的函数会执行所有指令,但console.log 返回hello undefined

对我来说(我的意思是我猜)这是回调,目前我知道如果您等待足够的时间,client.request(...)return 100% 的好价值;但即使使用async functionawait,lambda 看起来也很忙,无法等待 vimeo api 的响应。

谢谢,祝你有美好的一天

【问题讨论】:

    标签: node.js asynchronous callback aws-lambda vimeo-api


    【解决方案1】:

    await client.request() 不返回等待的承诺。

    你需要像这样自己做:

    exports.handler = async event => {
      const Vimeo = require('vimeo').Vimeo
      const client = new Vimeo('{client_id}', '{client_secret}', '{access_token}')
      console.log('client => ', client)
      console.log('event => ', event)
      const videoId = event.video_id
      const res = await new Promise((resolve, reject) => {
        client.request({
          method: 'GET',
          path: `/users/1234567890/videos/${videoId}`
        },
        function (error, body, statusCode, headers) {
          if (error) {
            console.log('error', error)
            reject(error)
            return
          }
          console.log('body', body)
          console.log('status code')
          console.log(statusCode)
          console.log('headers')
    
          console.log(headers)
          resolve(body)
        }
        )
      })
    
      console.log('hello', res)
      return 'ok'
    }
    
    

    【讨论】:

    • 非常感谢它的工作!正如你所说,需要承诺等待!
    猜你喜欢
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 2023-03-27
    • 1970-01-01
    • 2021-06-18
    • 2023-04-07
    相关资源
    最近更新 更多