为什么我的带有嵌套异步函数的 try-catch 异常没有抛出?

Why is my try-catch exception with nested async function not throwing?

我想获取一些图像,所以我写了一个基于 promise 的脚本来从所选图像中获取图像 url。但是,当提供无效的 url 时,它应该 return “获取错误”。但是相反(如我所见),应用程序崩溃了,因此 try-catch 块无法正常工作。

const Jimp = require("jimp");

function rgba(source, width, height) {
  return new Promise((resolve, reject) => {
    try {
      resolve((async () => {
        const image = await Jimp.read(source);
        const resized = image.resize(width, height);
        const rgbaArray = [];

        for (y = 0; y < height; y++) {
          for (x = 0; x < width; x++) {
            rgbaArray.push(Jimp.intToRGBA(resized.getPixelColor(x, y)));
          };
        };

        return rgbaArray;
      })());
    } catch {
      reject("Get Error");
    };
  });
};

// Returns correct result.
rgba(
  "https://upload.wikimedia.org/wikipedia/commons/9/9e/SpaceX_Crew-1_Launch_%28NHQ202011150029%29.jpg", 
  50, 
  50
).then(resolve => {
  console.log(resolve);
}).catch(reject => {
  console.log(reject);
}); 

// App crashes instead of logging "Get Error."
rgba(
  "improper_url", 
  50, 
  50
).then(resolve => {
  console.log(resolve);
}).catch(reject => {
  console.log(reject);
}); 

使用 try...catch 直接处理 async/await 调用。

function rgba(source, width, height) {
  return new Promise(async (resolve, reject) => {
    try {
      const image = await Jimp.read(source);
      const resized = image.resize(width, height);
      const rgbaArray = [];
      for (y = 0; y < height; y++) {
        for (x = 0; x < width; x++) {
          rgbaArray.push(Jimp.intToRGBA(resized.getPixelColor(x, y)));
        }
      }
      resolve(rgbaArray);
    } catch {
      reject('Get Error');
    }
  });
}

或者,做你的工作,让调用方方法处理可能的异常:

async function rgba(source, width, height) {
  const image = await Jimp.read(source);
  const resized = image.resize(width, height);
  const rgbaArray = [];
  for (y = 0; y < height; y++) {
    for (x = 0; x < width; x++) {
      rgbaArray.push(Jimp.intToRGBA(resized.getPixelColor(x, y)));
    }
  }
  return rgbaArray;
}

在调用方法中你可以轻松处理错误:

async function handler() {
  try {
    const result = await rgba(/* args */);
  } catch (e) {
    console.error(e);
  }
}

承诺处理:

function handlerPromise() {
  rgba(/* args */)
      .then(result => {
        console.log(result);
      })
      .catch(err => {
        console.error(err);
      });
}