【问题标题】:How to return response from async function correctly & push it into another object如何正确返回异步函数的响应并将其推送到另一个对象
【发布时间】:2022-01-06 06:50:53
【问题描述】:

我有一个 Angular 11.x 应用程序向后端系统执行 http 请求,该后端系统使用 FFMPEG 从视频文件(例如 mp4/mov)中读取数据,因为完成此异步请求需要 10 秒的处理时间。

为了更清楚,我对一些值进行了硬编码

// video-component.ts

let fileUrl = 'https://abc.s3.eu-west-2.amazonaws.com/video.mp4';
let fileSize = '56117299';
this.videoMetadata = this.videoService.getVideoMediaData(fileUrl, fileSize);

// if any errors found from the async response loop through them and push them into the following error which displays this on the frontend

/* I need to push the errors from the request above into this `errorMessages` variable
self.errorMessages['Instagram'].push({
    "message": "Video must be between 3-60 seconds in duration",
});
*/

// video.service.ts(在端点使用FFMPEG下载文件并获取元数据)

public getMetadata(file: string, size: string): Observable<any> {
    let params = new HttpParams();
    params = params.append('file', file);
    params = params.append('size', size);
    return this.http.get('post/media-check', { params })
        .pipe(map(response => {
            return response;
    }));
}

public getVideoMediaData(file, size) {
    return new Promise((resolve, reject) => {
        this.getMetadata(file, size).subscribe(
            data => {
                resolve(data);
            },
            errorResponse => {

            }
        );
    });
}

getMetadata 函数中的 post/media-check 命中 PHP 端点并返回类似于以下内容的以下响应。

{
   "status":"200",
   "data":{
      "video":{
         "container":"mov",
         "bitrate":338,
         "stream":0,
         "codec":"h264",
         "fps":3
      }
   },
   "errors":["Video must be at least 25 frames per second (fps)"],
   "responseType":"json",
   "response":"success"
}

如何从异步请求推送的后端响应中直接获取错误数组到self.errorMessages 变量中?

【问题讨论】:

标签: javascript json angular typescript angular11


【解决方案1】:

首先,您需要确保您的 video-service 正确处理错误。

public getVideoMediaData(file, size) {
    return new Promise((resolve, reject) => {
        this.getMetadata(file, size).subscribe(
            data => {
                resolve(data);
            },
            errorResponse => {
                // Reject the Promise and pass the error response in the rejection
                reject(errorResponse);
            }
        );
    });
}

然后在您的video-component 中,您可以像这样处理这种情况:

let fileUrl = 'https://abc.s3.eu-west-2.amazonaws.com/video.mp4';
let fileSize = '56117299';
try {
    this.videoMetadata = await this.videoService.getVideoMediaData(fileUrl, fileSize);
    // happy path - do something with this.videoMetadata
} catch(e) {
    // unhappy path - e = errorResponse
    const messages = errorResponse.errors.map(message => ({ message }));
    self.errorMessages['Instagram'].push(...messages);
}

【讨论】:

  • 感谢 Martin 使用 try-catch 也是个好主意
猜你喜欢
  • 2014-08-12
  • 1970-01-01
  • 1970-01-01
  • 2015-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-11
  • 1970-01-01
相关资源
最近更新 更多