vimeo.js icon indicating copy to clipboard operation
vimeo.js copied to clipboard

Promise support

Open erunion opened this issue 6 years ago • 1 comments

Using the library can, quite frankly, be a bit of a mess sometimes if you're doing sequential API calls. We should support promises.

erunion avatar Dec 11 '18 19:12 erunion

I needed this as well, so decided to write a simple utility function. It uses types found in the @types/vimeo package, and works great for typescript.

const promisifiedVimeoClient = (url: string | RequestOptions) => {
  return new Promise((resolve, reject) => {
    vimeoClient.request(url, (error, result) => error ? reject(error) : resolve(result) );
  });
}

If you don't use typescript, the code will look like this:

const promisifiedVimeoClient = (url) => {
  return new Promise((resolve, reject) => {
    vimeoClient.request(url, (error, result) => error ? reject(error) : resolve(result) );
  });
}

And the usage is the same regardless of whether you use typescript or javascript.

Async/await example

export const vimeoSearch = functions.https.onCall(async (data, context) => {
  const video_id = data.id;
  try {
    const video = awaiat promisifiedVimeoClient({
      method: 'GET',
      path: `/videos/${video_id}`
    });

    console.log(`video with id ${video_id}retrieved`, video);
  } catch ( error ) {
    console.error(`error getting video with video id ${video_id}`, error);
  }
});

If you're not comfortable using async/await yet, you can always use the promises the old school way .then / .catch

export const vimeoSearch = functions.https.onCall((data, context) => {
  const video_id = data.id;

  promisifiedVimeoClient({
    method: 'GET',
    path: `/videos/${video_id}`
  }).then(video => {
    console.log(`video with id ${video_id}retrieved`, video);
  }).catch( error => {
    console.error(`error getting video with video id ${video_id}`, error);
  });
});

Enjoy! :)

abdel-ships-it avatar Jul 04 '20 17:07 abdel-ships-it