Giải pháp cho các trình duyệt tuân thủ ECMAScript 2017
Lưu ý: điều này cũng sẽ hoạt động nếu bạn đang sử dụng một bộ chuyển mã như Babel.
'use strict';
function imageLoaded(src, alt = '') {
return new Promise(function(resolve) {
const image = document.createElement('img');
image.setAttribute('alt', alt);
image.setAttribute('src', src);
image.addEventListener('load', function() {
resolve(image);
});
});
}
async function runExample() {
console.log("Fetching my cat's image...");
const myCat = await imageLoaded('https://placekitten.com/500');
console.log("My cat's image is ready! Now is the time to load my dog's image...");
const myDog = await imageLoaded('https://placedog.net/500');
console.log('Whoa! This is now the time to enable my galery.');
document.body.appendChild(myCat);
document.body.appendChild(myDog);
}
runExample();
Bạn cũng có thể đợi tất cả các hình ảnh được tải.
async function runExample() {
const [myCat, myDog] = [
await imageLoaded('https://placekitten.com/500'),
await imageLoaded('https://placedog.net/500')
];
document.body.appendChild(myCat);
document.body.appendChild(myDog);
}
Hoặc sử dụng Promise.all
để tải chúng song song.
async function runExample() {
const [myCat, myDog] = await Promise.all([
imageLoaded('https://placekitten.com/500'),
imageLoaded('https://placedog.net/500')
]);
document.body.appendChild(myCat);
document.body.appendChild(myDog);
}
Thông tin thêm về Lời hứa .
Tìm hiểu thêm về các chức năng "Async" .
Thêm về nhiệm vụ phá hủy .
Thông tin thêm về ECMAScript 2015 .
Thông tin thêm về ECMAScript 2017 .
img
đối tượng, ví dụ như trong một mảng trong phạm vi cha.