尽管等待已久,诺言仍未解决

时间:2019-02-10 15:03:48

标签: javascript node.js

我想从某些图像中获取像素并将其作为数组返回。对于图像处理,我使用https://www.npmjs.com/package/jimp。 Jimp有一个异步函数jimp.read(filePath),需要等待处理。我的图片阅读器模块:

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,这是一个async函数,正在等待jimp阅读器。

为什么它会返回承诺但不能解决?我是否必须等待每个功能和整个模块...?

5 个答案:

答案 0 :(得分:2)

由于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);
}

答案 1 :(得分:0)

您还需要await函数getInformationFromImageFile()

答案 2 :(得分:0)

async/await就像承诺一样。您必须像处理承诺一样处理异步回报。

无论何时调用异步函数,您都必须在另一个异步函数中等待它,或者像对待诺言一样使用.then()

// 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);
}

答案 3 :(得分:0)

异步/等待始终返回Promise,因此您可以执行以下操作:

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

答案 4 :(得分:-1)

正如其他成员所说,您的函数必须为awaited,因此它将返回承诺result

如果您想避免使用awaiting函数,则可以通过同步方式获得promise结果,如下所示:

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