Promise加载多张图片

function loadImg (url) {
  return new Promise((resolve, reject) => {
    const img = document.createElement('img')
    img.src = url
    img.onload = () => {
      resolve(img)
    }
    img.onerror = () => {
      reject(new Error(`图片加载失败:${url}`))
    }
  })
}
loadImg('https://img4.sycdn.imooc.com/61ac6d6b0001f09407680768-140-140.jpg')
  .then(img => {
    console.log('img1.width')
    console.log(img.width)
    return loadImg('https://img4.sycdn.imooc.com/szimg/5eddd7aa09cfdb1c12000676-360-202.png')
  })
  .then(img => {
    // 这里then会接收到上一个then的return
    console.log('img2.width')
    console.log(img.width)
  })

Promise解决回调函数地狱问题

results matching ""

    No results matching ""