Skip to content

Instantly share code, notes, and snippets.

@hacke2

hacke2/lightpromise.js

Forked from wintercn/lightpromise.js
Last active Aug 29, 2015
Embed
What would you like to do?
function get(uri) {
return http(uri,'GET');
}
function post(uri,data) {
if(typeof data === 'object' && !(data instanceof String || (FormData && data instanceof FormData))) {
var params = [];
for(var p in data) {
if(data[p] instanceof Array) {
for(var i = 0; i < data[p].length; i++) {
params.push( encodeURIComponenet(p) + '[]=' + encodeURIComponenet(data[p][i]);
}
} else {
params.push( encodeURIComponenet(p) + '=' + encodeURIComponenet(data[p]);
}
}
data = params.join('&');
}
return http(uri,'POST',data);
}
function http(uri,method,data) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method,uri,true);
xhr.send(data);
xhr.addEventListener('readystatechange',function(e){
if(xhr.readyState === 4) {
if(xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(xhr);
}
}
})
})
}
function wait(duration) {
return new Promise(function(resolve, reject) {
setTimeout(resolve,duration);
})
}
function waitFor(element,event,useCapture){
return new Promise(function(resolve, reject) {
element.addEventListener(event,resolve,useCapture)
})
}
function loadImage(src) {
return new Promise(function(resolve, reject) {
var image = new Image;
image.src = src;
image.addEventListener('load',function() {
resolve(image);
});
image.addEventListener('error',reject);
})
}
function runScript(src) {
return new Promise(function(resolve, reject) {
var script = document.createElement('script');
script.src = src;
script.addEventListener('load',resolve);
script.addEventListener('error',reject);
(document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.