function imgLoad(url) {
// 用两个参数, resolve和reject
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', url)
request.responseType = 'blob'
// onload
request.onload = function() {
if (request.status === 200) {
// 成功响应
resolve(request.response);
} else {
reject(Error(request.statusText));
}
}
// onerror
request.onerror = function() {
reject(Error('加载失败'))
};
// 发送请求
request.send()
})
}
var body = document.querySelector('body');
var myImage = new Image();
imgLoad('blob:https://mdn.github.io/f84ebba6-8b10-4165-8704-47923e6129e1')
.then(function(response) {
var imageURL = window.URL.createObjectURL(response)
myImage.src = imageURL
body.appendChild(myImage)
},
function(Error) {
console.log(Error)
})
参考:
https://mdn.github.io/js-examples/promises-test/
网友评论