简体   繁体   English

执行 request.get 后在 .map 中使用返回值

[英]Use return value in a .map after performing request.get

So basically, due to the security, I need to convert image (from the url) to the base64.所以基本上,出于安全考虑,我需要将图像(来自 url)转换为 base64。

So far I have two functions.到目前为止,我有两个功能。 One function is converting the image from the url to the Base64 and the other one is mapping over the database and is replacing the default url to the base64 format.一个功能是将图像从 url 转换为 Base64,另一个是映射数据库并将默认 url 替换为 base64 格式。 I miss the last piece of the puzzle, how to use the return value from the 1st function in the second one - I want to replace 'test' in the second function with the result of conversion from url to base64.我错过了拼图的最后一块,如何在第二个函数中使用第一个函数的返回值 - 我想用从 url 转换为 base64 的结果替换第二个函数中的“test”。

 public async convertUrlToBase64(): Promise<any> {
    const request = require('request').defaults({ encoding: null });

    await request.get(
      'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Ray_and_Maria_Stata_Center_%28MIT%29.JPG/2560px-Ray_and_Maria_Stata_Center_%28MIT%29.JPG',
      function (
        error: any,
        response: { statusCode: number; headers: { [x: string]: string } },
        body: ArrayBuffer | SharedArrayBuffer,
      ) {
        return 'data:' + response.headers['content-type'] + ';base64,' + Buffer.from(body).toString('base64');
      },
    );
  }

  public mapUriToBase64(note: any): any {
    return {
      ...note,
      images: note.images.map((image: File) => {
        return {
          ...image,
          uri: 'test',
        };
      }),
    };
  }
}

You basically need to wrap it with the Promise in order to get the returned value from your call.您基本上需要用 Promise 包装它,以便从您的调用中获取返回值。

public convertUrlToBase64(): any {
    const request = require('request').defaults({ encoding: null });

    return new Promise(function (resolve, reject) {
      request.get(
        'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Ray_and_Maria_Stata_Center_%28MIT%29.JPG/2560px-Ray_and_Maria_Stata_Center_%28MIT%29.JPG',
        function (
          error: any,
          response: { statusCode: number; headers: { [x: string]: string } },
          body: ArrayBuffer | SharedArrayBuffer,
        ) {
          const data = 'data:' + response.headers['content-type'] + ';base64,' + Buffer.from(body).toString('base64');
          resolve(data);
        },
      );
    });
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM