Promises are meant to be asynchronous
New Promise takes two arguments, resolve and reject. Then executes the resolve callback,.catch executes reject, and.finally executes the result of a success or failure
Promise instance: if the image loads successfully, it will be displayed; if it fails, it will raise the image error
cosnt imgAdd = 'img'
const imgPromise = (url) = > {
return new Promise ((resolve,reject) = > {
const img = new Image()
img.src = url
img.onload = () = > {
resolve(img)
}
img.onerror = () = > {
reject(new Error('Picture error'))
}
})
}
imgPromise(imgAdd)
.then(img= > {
docoument.body.appendChild(img)
})
.catch(err= > {
document.body.innerHTML = err
})
Copy the code