承诺没有被解决,尽管已经等待。

3
我想从一些图片中获取像素并将它们作为数组返回。我使用https://www.npmjs.com/package/jimp处理图像。Jimp有一个异步函数jimp.read(filePath),需要使用await进行处理。我的图像读取器模块:
const config = require('./configuration.json');
const fs = require('fs');
const path = require('path');
const jimp = require('jimp');

module.exports = readImages;

function readImages() { // Reads the image files and extracts the colors
    const files = getFilesFromDirectory();
    const imageFiles = filterForImageFiles(files);
    return getInformationFromImageFiles(imageFiles);
}

function getFilesFromDirectory() { // Reads all the files from the directory provided from the configuration file
    return fs.readdirSync(config.dirPath);
}

function filterForImageFiles(files) { // Filters an array of files for .png and .jpg files
    return files.filter(file => {
        const fileExtension = path.extname(file);
        const isPngFile = fileExtension === '.jpg';
        const isJpgFile = fileExtension === '.png';
        return isPngFile || isJpgFile;
    });
}

function getInformationFromImageFiles(imageFiles) { // Maps image files to image information
    return imageFiles.map(imageFile => getInformationFromImageFile(imageFile));
}

async function getInformationFromImageFile(imageFile) { // Extracts information from an image file
    const filePath = path.join(config.dirPath, imageFile);
    const image = await jimp.read(filePath);
    return getColorsFromImage(image);
}

function getColorsFromImage(image) { // Extracts the colors from an image file
    const { width, height } = image.bitmap;
    const colors = [,];
    for (let x = 0; x < width; x++) {
        for (let y = 0; y < height; y++) {
            const intColor = image.getPixelColor(x, y);
            const rgbaColor = jimp.intToRGBA(intColor);
            colors[x, y] = rgbaColor;
        }
    }
    return colors;
}

当我运行这段代码时,我会收到一个包含两个项目的数组(因为我提供了两张图片)。这两个项目都是Promise { <pending> }。请查看getInformationFromImageFile,它是一个异步函数,等待jimp reader完成。
为什么它会返回一个promise而不是解决它?我是否需要等待每个函数和整个模块...?

await jimp.read(filePath) 是有效的,它正在等待调用得到解决。但是,在 getInformationFromImageFiles 中你没有等待调用 getInformationFromImageFile(imageFile) 的返回。 - Olian04
你希望 readImages 返回什么? - Mark
图像文件数组 - Question3r
@Olian04 抱歉,我仍然得到了 Promise。 - Question3r
5个回答

4

getInformationFromImageFile 标记为 async,因此它将返回一个 Promise,所以必须等待它。 在调用的地方需要使用 await。以下更改应该解决问题:

async function getInformationFromImageFiles(imageFiles) {
    const imageInfos = [];
    for (let i = 0; i < imageFiles.length; i++) {
        const imageFile = imageFiles[i];
        imageInfos.push(await getInformationFromImageFile(imageFile));
    }

    return imageInfos;
}

async function readImages() {
    const files = getFilesFromDirectory();
    const imageFiles = filterForImageFiles(files);
    return await getInformationFromImageFiles(imageFiles);
}

是的,抱歉我的错@MarkMeyer,我已经编辑了答案,希望现在是正确的。 - peter554
抱歉,但我仍然得到一个 Promise。 - Question3r
@Question3r 当调用readImages时,您需要等待(或使用“then”语法),因为它现在是异步的,所以会返回一个Promise。您是否等待readImages - peter554
1
啊,谢谢,现在它可以工作了。但请更新你的 getInformationFromImageFiles(imageFiles) 函数,imageFiles.push 应该改为 imageInfos.push 才能让它正常工作 :) - Question3r

0

你还需要await函数getInformationFromImageFile()


抱歉,我仍然得到了 Promise。 - Question3r

0

async/await 就像 Promise 一样。你必须像处理 Promise 一样处理异步返回。

每当调用异步函数时,你必须在另一个异步函数中等待它或者使用 .then(),就像使用 Promise 一样。

// make this function async
async function readImages() {
  // Reads the image files and extracts the colors
  const files = getFilesFromDirectory();
  const imageFiles = filterForImageFiles(files);
  // the next line is an async call - so await it
  const images = await getInformationFromImageFiles(imageFiles); // array of images
  return images;
}

function getFilesFromDirectory() {
  // Reads all the files from the directory provided from the configuration file
  return fs.readdirSync(config.dirPath);
}

function filterForImageFiles(files) {
  // Filters an array of files for .png and .jpg files
  return files.filter((file) => {
    const fileExtension = path.extname(file);
    const isPngFile = fileExtension === '.jpg';
    const isJpgFile = fileExtension === '.png';
    return isPngFile || isJpgFile;
  });
}

// make this function async
async function getInformationFromImageFiles(imageFiles) {
  // promisify all async returns
  return Promise.all(imageFiles.map((imageFile) => getInformationFromImageFile(imageFile)));
}

// return async
async function getInformationFromImageFile(imageFile) {
  // Extracts information from an image file
  const filePath = path.join(config.dirPath, imageFile);
  const image = await jimp.read(filePath);
  return getColorsFromImage(image);
}

0

异步/等待总是返回Promise,所以你可以像这样做:

Promise
  .all(readImages())
  .then(imd => console.log(imd))
  .catch(error => console.log(error));`

-1

正如其他成员所说,您的函数需要被awaited,因此它将返回承诺result

如果您想避免awaiting函数,可以以同步方式获取承诺结果,像这样:

let x = new Promise(function(){
//code
});
x.then(function(data){
   //Promise resolved, do something
}).then(function(err){
   //Promise rejected, do something
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接