【问题标题】:Implementing Recursive Function with Async and Await with Angular 10使用 Angular 10 使用 Async 和 Await 实现递归函数
【发布时间】:2021-03-25 19:25:56
【问题描述】:

我正在尝试以 base64 格式获取一组图像。为了利用最大带宽,我们计划一张接一张地获取图像。

下面是代码

const input = ['url1']; //Array of image urls

this.recursiveFunction(input, 0, []).then((res: any) => {
    console.log(res);
});

async recursiveFunction(urls: any, index = 0, responses: any = []){
    const url = urls[index];
    return await this.srv.getData({ url: url }).subscribe((response: any) => {
        responses.push(response);
        if (responses.length !== urls.length) {
            return this.recursiveFunction(urls, index + 1, responses);
        }
        return responses;
    });

}

使用 6 张图片进行测试,服务调用运行良好。

但我看到 console.log(res) 立即输出该函数被调用(在第一次服务调用之前),如下所示

响应包含所有 6 张图片 base64 数据。如何在最后一次服务调用结束时获取响应

【问题讨论】:

    标签: angular async-await


    【解决方案1】:

    将您的方法更改为:-

    async recursiveFunction(urls: any){
        const url = urls[index];
        return await getImages(urls);
    }
    
    
    
    async getImages(urls: any) {
           const responses = [];
           for(const url of urls) {
            const res = await this.srv.getData({ url: url }).toPromise();
            responses.push(res);
           }
           return responses;
       }
    

    现在您可以只传递 url 数组,您将获得图像作为响应。

    【讨论】:

    • 你应该使用当前的,它更高效,更干净。
    • 当然。我将在折射时替换此代码。这是为了演示批准。
    • 我在递归函数 resolve(await(...)) 上遇到此错误“'await' 表达式只允许在异步函数中和模块的顶层使用。”
    • @AlaksandarJesusGene 已经更新了答案,现在你应该不会收到错误了。
    【解决方案2】:

    如果你不想使用 async 和 await,你可以使用 switchMap 并点击

    myfunction(index){
        return index<this.data.length?this.obs$(index).pipe(
           tap(res=>this.res[index]=res),
           switchMap(_=>{
             index++;
             return this.myfunction(index)
           })):of(null)
        
      }
    

    只需要订阅myFunction

     ngOnInit(){
        this.myfunction(0).subscribe()
      }
    

    stackblitz

    【讨论】:

      猜你喜欢
      • 2020-07-26
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多