Skip to content

手写用 Promise 加载一张图片

使用 Promise 来解决 callback hell 回调地狱的问题,举例演示

先定义一个 Promise 的函数

js
function loadImg(src) {
  return new Promise((resolve, reject) => {
    const img = document.createElement('img');
    img.onload = () => {
      console.log(1);
      resolve(img);
    };
    img.onerror = () => {
      console.log(2);
      const err = new Error(`图片加载失败 ${src}`);
      reject(err);
    };
    console.log(3);
    img.src = src;
  });
}

然后怎么使用

js
const url1 =
  'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png';
const url2 =
  'https://box.bdimg.com/static/fisp_static/common/img/searchbox/logo_news_276_88_1f9876a.png';
loadImg(url1)
  .then((img1) => {
    console.log('img1.width ' + img1.width);
    return img1;
  })
  .then((img1) => {
    console.log('img1.height ' + img1.height);
    return loadImg(url2); //promise实例解决 callback hell
  })
  .then((img2) => {
    console.log('img2.width ' + img2.width);
    return img2;
  })
  .then((img2) => {
    console.log('img2.height ' + img2.height);
  })
  .catch((err) => {
    console.log(err);
  });
// 3
// 1
// img1.width 540
// img1.height 258
// 3
// 1
// img2.width 276
// img2.height 88

基于 MIT 许可发布