Search code examples
node.jsasynchronouscallbackaws-lambdavimeo-api

Lambda node "hello undefined" async/await don't work?


Here is my problem : I would like to call the Vimeo api inside my aws-lambda function (nodejs 12) to get some information/data about a video (like : duration, title, ...).

Here is my code :

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';
};

To try it, I launch few tests. The lambda return ok so I know that my function go through all instructions but the console.log return hello undefined.

For me (I mean I guess) It's the callback, currently I know at 100% the client.request(...)return the good value if you wait enough time; but even with async function and await the lambda look too busy to wait the response of the vimeo api.

thx and have a good day


Solution

  • await client.request() doesn't return a promise to wait.

    You need to do it by yourself like this:

    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'
    }