// promise 載入一個圖片示例function loadImage(url){ new Promise(function(resolve, reject){ var img = new Image() img.onload = function(){ resolve(img) } img.o ...
// promise 載入一個圖片示例
function loadImage(url){
new Promise(function(resolve, reject){
var img = new Image()
img.onload = function(){
resolve(img)
}
img.onerror = function(){
reject(new Error('could not load' + url))
}
img.src = url
})
}
// promise 實現ajax請求
var getJSON= function(url){
var promise = new Promise(function(resolve, reject){
var client = new XMLHttpRequest();
client.open('GET', url)
client.onreadystatechange = handler
client.responseType = 'json'
client.setRequestHeader('Accept', 'application/json')
client.send()
function handler(){
if(this.readyState !== 4){
return
}
if(this.status === 200){
resolve(this.response)
}else{
reject(new Error(this.statusText))
}
}
})
}