โซลูชั่นสำหรับเบราว์เซอร์ที่ใช้กับ ECMAScript 2017
หมายเหตุ: สิ่งนี้จะใช้ได้หากคุณใช้ transpiler เช่น 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();
คุณอาจรอโหลดรูปภาพทั้งหมด
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);
}
หรือใช้Promise.allเพื่อโหลดมันแบบขนาน
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);
}
สัญญาเพิ่มเติมเกี่ยวกับ
เพิ่มเติมเกี่ยวกับ "Async" ฟังก์ชั่น
เพิ่มเติมเกี่ยวกับการกำหนด destructuring
เพิ่มเติมเกี่ยวกับ ECMAScript 2015
เพิ่มเติมเกี่ยวกับ ECMAScript 2017
imgวัตถุเช่นในอาร์เรย์ในขอบเขตหลัก