为什么我的承诺无法解决?

时间:2018-02-14 19:25:46

标签: javascript node.js es6-promise

我有以下功能调整图像大小。

promise应该在onload部分代码中解析,但由于某些原因它不会......

import Pica from 'pica';

const pica = new Pica();

export default ({ src, size }) =>
  new Promise((resolve, reject) => {
    const [width, height] = size.split('x');
    const from = new Image();
    const to = document.createElement('canvas');
    const options = {
      width,
      height,
    };

    from.onload = async () => {
      try {
        const canvas = await pica.resize(from, to, options);
        resolve(canvas);
      } catch (e) {
         reject(e);
      }
    };

    from.src = src;
  });

我使用此函数来获取一个图像的不同大小版本的数组。我使用Promise.all()来实现这一目标。

以下是我调用此功能的代码:

    ...
    const img = ...
    sizes.map(size => {
      promisesArray.push(resizeImage({ img, size }));
    });

    Promise.all(promisesArray).then(data => console.log(data))

我已尝试console.log(resizeImage({ img, size })),并获得pending状态无法解决的承诺。

我还假设它是由Pica引起的。所以我试图简化这个功能,但它也没有工作:

// no extra code
export default ({ src, size }) =>
  new Promise((resolve, reject) => {    
    const from = new Image();

    from.onload = () => {
      // what's wrong here?
      resolve('hello');
    };

    from.src = src;
  });

1 个答案:

答案 0 :(得分:2)

除了列出onload之外,您应该始终为onerror添加一个监听器,因为Image可能无法加载。

如果您在console.log回调中添加onerror,我怀疑您会看到您已将src个无效的onerror传递给您的一个或多个来电和图片只是无法加载。

作为演示如何连接const loadImg = (src) => new Promise((resolve, reject) => { const img = new Image(); img.onload = () => resolve(img); img.onerror = (err) => reject(err); img.src = src; }); // This should succeed loadImg('data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7').then( () => console.log('Image loaded!'), () => console.log('Image failed!'), ); // This will fail loadImg('invalid-url').then( () => console.log("How did that load?"), () => console.log("That wasn't an image!"), );回调的示例(忽略与您的问题无关的调整代码):



clang-format