Promise的高级用法

  1. Promise.all()
    所有的promise实例都resolve后再执行then
    案例:所有图片加载完成后再加入到页面
{
  function loadImg(src) {
    return new Promise((resolve, reject) => {
      let img = document.createElement('img');
      img.src = src;
      img.onload = function() {
        resolve(img);
      }
      img.onerror = function(err) {
        reject(err)
      }
    })
  }

  function showImgs(imgs) {
    imgs.forEach(img => {
      document.body.appendChild(img)
    })
  }

  Promise.all([
    loadImg('http://img4.imgtn.bdimg.com/it/u=1020383179,3062284491&fm=26&gp=0.jpg'),
    loadImg('http://img1.imgtn.bdimg.com/it/u=1992085767,102835282&fm=26&gp=0.jpg'),
    loadImg('http://img4.imgtn.bdimg.com/it/u=967395617,3601302195&fm=26&gp=0.jpg')
  ]).then(showImgs)
}
  1. Promise.race()
    所有实例中,只要有一个实例完成了就可以then
{
  function loadImg(src) {
    return new Promise((resolve, reject) => {
      let img = document.createElement('img');
      img.src = src;
      img.onload = function() {
        resolve(img);
      }
      img.onerror = function(err) {
        reject(err)
      }
    })
  }

  function showImgs(imgs) {
    imgs.forEach(img => {
      document.body.appendChild(img)
    })
  }

  Promise.race([
    loadImg('http://img4.imgtn.bdimg.com/it/u=1020383179,3062284491&fm=26&gp=0.jpg'),
    loadImg('http://img1.imgtn.bdimg.com/it/u=1992085767,102835282&fm=26&gp=0.jpg'),
    loadImg('http://img4.imgtn.bdimg.com/it/u=967395617,3601302195&fm=26&gp=0.jpg')
  ]).then(showImgs)
}

你可能感兴趣的:(es6)