# Promisification of an async code in JavaScript

Since promises have been around in JavaScript not for a long time, some asynchronous functionality may not support promises. In this case, it is useful to create a promise wrapper over such a code, since it is much more convenient to use promises. Such a transformation is called promisification.

An example of functionality that doesn't support promises is an image loading, which we have already discussed in previous lessons:

`let image = document.createElement('img'); image.src = 'img.png'; image.addEventListener('load', function() { document.body.appendChild(image); }); image.addEventListener('error', function() { console.log('image load error'); });`

Let's implement a promisification of this code by wrapping it in a function that returns the promise:

`function loadImage(path) { return new Promise(function(resolve, reject) { let image = document.createElement('img'); image.src = path; image.addEventListener('load', function() { resolve(image); }); image.addEventListener('error', function() { reject(new Error('image "' + path + '" load error')); }); }); }`

We can use our function like this:

`loadImage('img.png').then(function(image) { document.body.appendChild(image); }).catch(function(error) { console.log(error); });`

On your own, without looking into my code, perform the image loading promisification. Test the resulting code.

Let the paths to the images be stored in an array:

`let paths = ['img1.png', 'img2.png', 'img3.png'];`

Write a code that will wait for all the images to finish loading and then add them in a loop to the end of the body.

Given the following code:

`window.addEventListener('DOMContentLoaded', function() { console.log('dom loaded'); });`

Perform this code promisification.

← →
↑
en ru