ECMAScript 2017 호환 브라우저를위한 솔루션
참고 : 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);
}
약속에 대해 자세히 알아보십시오 .
"비동기"기능에 대한 추가 정보 .
구조 지정 할당에 대해 자세히 알아보십시오 .
ECMAScript 2015에 대해 자세히 알아보십시오 .
ECMAScript 2017에 대해 자세히 알아보십시오 .
img개체에 대한 참조를 유지하십시오 ( 예 : 부모 범위의 배열).