Home > other >  How to get the value of a callback outside the upload function of the Vimeo class?
How to get the value of a callback outside the upload function of the Vimeo class?

Time:03-16

I'm very new to js and I'm learning Nestjs. I'm building an API to work with the Vimeo API using their Vimeo lib. To upload a video, the Vimeo class has a method called upload:

upload(
        file: string | File,
        params: object,
        completeCallback: UriCallback,
        progressCallback: ProgressCallback | undefined,
        errorCallback: ErrorCallback,
    ): void;
    upload(
        file: string | File,
        completeCallback: UriCallback,
        progressCallback: ProgressCallback | undefined,
        errorCallback: ErrorCallback,
    ): void;

On my service, I used it like:

async uploadVideo(@Body() video: UploadVideoDto): Promise<string> {
    let videoUri: string;
    this.client.upload(
      video.pathToFile,
      {
        name: video.name,
        description: video.description,
      },
      function (uri) {
        console.log(uri);
        videoUri = uri;
      },
      function (bytesUploaded, bytesTotal) {
        console.log(bytesUploaded, bytesTotal);
      },
      function (error) {
        throw new Error(error);
      },
    );
    return videoUri;
  }

The function (uri) { console.log(uri) } is the callback function when the upload finishes and it gives the uri that the video was uploaded to. I tried to get it on my controller, like this:

 @Post('/upload')
  async upload(@Body() video: UploadVideoDto) {
    await this.appService.uploadVideo(video).then(function (uri): void {
      console.log(uri);
    });
  }

The problem is that the console.log(uri) always prints undefined. How can I get that callback return from my service to my controller?

CodePudding user response:

if uploadVideo should return a Promise that resolves to an string (the uri), it could be like this:

async uploadVideo(video: UploadVideoDto): Promise<string> {
  return new Promise<string>((resolve, reject) => {

    this.client.upload(
      video.pathToFile,
      {
        name: video.name,
        description: video.description,
      },
      function (uri) {
        resolve(uri)
      },
      function (bytesUploaded, bytesTotal) {
        console.log(bytesUploaded, bytesTotal);
      },
      function (error) {
        reject(error)
      },
    );

  })
}

Learn about JS async/await feature.

  • Related