我想获取一些图像,所以我编写了一个基于 Promise 的脚本来从选定的图像 url 获取图像。但是,当提供无效的 url 时,它应该返回“Get Error”。但是相反(如我所见),应用程序崩溃了,因此 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);
});