-1

I'm new to nodejs.

I want to get my video list using vimeo api.(https://developer.vimeo.com/api/guides/start)

In the following code, I want to return the body or error of the callback function rather than print it.

function get_Vimeo_Data() {


  let Vimeo = require('vimeo').Vimeo;
  let client = new Vimeo("api_key", "key");
  client.request({
    method: 'GET',
    path: '/me/videos'
  }, function (error, body, status_code, headers) {
    if (error) {
      console.log(error)
    }
    console.log(body)
  });
}

I tried to use promises by referring to various codes, but all failed.

It seems that vimeo api must use callback.

김양우
  • 29
  • 4
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – jonrsharpe Mar 08 '22 at 17:16

1 Answers1

1
function get_Vimeo_Data() {
  let Vimeo = require("vimeo").Vimeo;
  let client = new Vimeo("api_key", "key");
  return new Promise((resolve, reject) => {
    client.request(
      {
        method: "GET",
        path: "/me/videos",
      },
      function (error, body, status_code, headers) {
        if (error) {
          //reject(error);
          resolve(error);
        }
        resolve(body);
      }
    );
  });
}

if you do this, then u can just call the function anywhere like this,

await get_Vimeo_Data()

note: I've commented out the reject(error), because u wanted the error to also be returned rather than being thrown as an exception

hafizur046
  • 306
  • 3
  • 8
  • Thank you for answer. But how do I access the body in other func? Sorry I'm new to nodejs. It seems that the usage is very different from other languages. – 김양우 Mar 08 '22 at 17:32
  • you have to `await` for the asynchronous block of code to resolve, maybe you should learn about how promises and async-await work in javascript, – hafizur046 Mar 08 '22 at 17:34
  • I try "return await get_Vimeo_Data();" but return "Promise { }" – 김양우 Mar 08 '22 at 17:35
  • in the function where u are using the await keyword to, `return await get_Vimeo_Data()` is an asynchronous function, and asynchronous functions would always obviously return a promise – hafizur046 Mar 08 '22 at 17:42
  • if you want to use the data, you would have to use it "inside" an asynchronous function, its how javascript works `const data = await get_Vimeo_Data(); //do stuffs with the data` – hafizur046 Mar 08 '22 at 17:46
  • The call to await get_Vimeo_Data() should be in an async block – Alaindeseine Mar 08 '22 at 18:20