Home > Web Front-end > JS Tutorial > body text

Using Promise in Javascript to solve aynchronous loading(image, css, js, etc.)

Barbara Streisand
Release: 2024-11-09 08:59:02
Original
859 people have browsed it

Using Promise in Javascript to solve aynchronous loading(image, css, js, etc.)

Sometimes we need to complete some operations after loading static resources. Using callback function is a common method, but this approach may generate multi-callback functions, making the code struction more complex. So we can use Promise to deal with this issue.

Example(loading an image)

function loadImg(imgSrc) {
  return new Promise(function(resolve, reject){
    img.load = () => {
      // asynchronous code here
      resolve()
    }

    img.onError = () => {
      reject()
    }
  })
}


loadImg('src.jpg').then(()=>{
  // operations after loading image here
}).catch(()=>{
 // error handling
})
Copy after login

Example of loading mutiple images

function loadImg(imgSrc) {
  return new Promise(function(resolve, reject){
    img.load = () => {
      // asynchronous code here
      resolve()
    }

    img.onError = () => {
      reject()
    }
  })
}

const imgList = ['1.jpg', '2.jpg', '3.jpg', '4.jpg']
let imgLoadingPromise = []
for(let img of imgList) imgLoadingPromise.push(loadImg(img))

Promise.all(imgLoadingPromise).then(()=>{
  // operations after loading image here
}).catch(()=>{
 // error handling
})
Copy after login

Promise.all() receives an array of promises that only becomes fullfilled state when all Promise become fullfilled state

The above is the detailed content of Using Promise in Javascript to solve aynchronous loading(image, css, js, etc.). For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template