我如何使该函数异步以允许我返回某些东西?

时间:2019-04-10 10:43:48

标签: javascript image asynchronous image-recognition

试图编写一个可以导出的函数,这样我就可以在各个地方调用它并轻松地将其传递给图像。

我尝试了各种将功能合并为异步并在需要时使用await的方法。只是似乎并不太正确。我已删除了尝试的异步/等待功能,因此您可以事先查看代码的外观。

const getPixels = require("get-pixels");

const imgLink = 'https://upload.wikimedia.org/wikipedia/commons/8/8a/LGBT_Rainbow_Flag.png';

exports.analyzeImg = imgLink => {
  getPixels(imgLink, (err, pixels) => {
    if (err) {
      console.log("Bad image path");
      return;
    }

    const copyPixelArr = [...pixels.data];

    const rgbExtraction = grid => {
      const allRed = [];
      const allGreen = [];
      const allBlue = [];
      const allWhite = [];

      for (let i = 0; i < grid.length; i += 4) {
        allRed.push(grid[i]);
      }
      for (let i = 1; i < grid.length; i += 4) {
        allGreen.push(grid[i]);
      }
      for (let i = 2; i < grid.length; i += 4) {
        allBlue.push(grid[i]);
      }
      for (let i = 3; i < grid.length; i += 4) {
        allWhite.push(grid[i]);
      }

      const avgRed =
        allRed.reduce((acc, val) => {
          acc += val;
          return acc;
        }, 0) / allRed.length;
      const avgGreen =
        allGreen.reduce((acc, val) => {
          acc += val;
          return acc;
        }, 0) / allGreen.length;
      const avgBlue =
        allBlue.reduce((acc, val) => {
          acc += val;
          return acc;
        }, 0) / allBlue.length;
      const avgWhite =
        allWhite.reduce((acc, val) => {
          acc += val;
          return acc;
        }, 0) / allWhite.length;

      return {
        r: avgRed,
        g: avgGreen,
        b: avgBlue,
        w: avgWhite
      };
    };
    const data = rgbExtraction(copyPixelArr);
    console.log(data);
    return data;
  });
};

当前console.log(data)返回我想要的东西,但是返回数据;未定义,因为它在尝试返回之前不等待其他函数运行。

0 个答案:

没有答案