Skip to content

Instantly share code, notes, and snippets.

@GianlucaGuarini
Last active July 25, 2016 06:19
Show Gist options
  • Save GianlucaGuarini/34e095c892952667a1d01f4ef04e35b0 to your computer and use it in GitHub Desktop.
Save GianlucaGuarini/34e095c892952667a1d01f4ef04e35b0 to your computer and use it in GitHub Desktop.
Simple script to promisify the API of any javascript Object - It's an experiment don't use it in production!!!!

Simple script to promisify the API of any javascript Object - It's an experiment don't use it in production!!!!

// simply...
window.promise.onload.then(() => console.log('loaded!'))

// or...
var img2 = new Image()
img2.promise.onload.then(() => console.log('Image loaded!'))
img2.crossOrigin = 'anonymous'
img2.src = 'https://placekitten.com/200/300'

var img = new Image()
img.promise.onerror.then(() => console.log('oh please! I can\'t load this!'))
img.src = 'trump.jpg'

Promise.all([
  img.promise.onerror,
  img2.promise.onload
]).then(() => {
	console.log('Rock and roll!')
})

demo

Object.defineProperty(Object.prototype, 'promise', {
get: function() {
return new Proxy({}, {
get: (target, name) => {
return new Promise((resolve) => {
this[name] = resolve
})
}
})
},
configurable: true
})
@GianlucaGuarini
Copy link
Author

This code was optimized and included in https://github.com/GianlucaGuarini/allora

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment