使用Promise封装异步图片加载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function loadImageAsync(url) { return new Promise(function(resolve, reject) { const image = new Image();
image.onload = function() { resolve(image); };
image.onerror = function() { reject(new Error('Could not load image at ' + url)); };
image.src = url; }); }
|
使用Promise对象实现AJAX操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| const getJSON = function(url) { const promise = new Promise(function(resolve, reject){ const handler = function() { if (this.readyState !== 4) { return; } if (this.status === 200) { resolve(this.response); } else { reject(new Error(this.statusText)); } }; const client = new XMLHttpRequest(); client.open("GET", url); client.onreadystatechange = handler; client.responseType = "json"; client.setRequestHeader("Accept", "application/json"); client.send();
});
return promise; };
getJSON("/posts.json").then(function(json) { console.log('Contents: ' + json); }, function(error) { console.error('出错了', error); });
|
上面代码中,getJSON是对 XMLHttpRequest 对象的封装,用于发出一个针对 JSON 数据的 HTTP 请求,并且返回一个Promise对象。需要注意的是,在getJSON内部,resolve函数和reject函数调用时,都带有参数。