Skip to content

Instantly share code, notes, and snippets.

@antife-yinyue
Forked from wintercn/lightpromise.js
Last active August 29, 2015 14:14
Show Gist options
  • Save antife-yinyue/86b0bfcde44bec798e2d to your computer and use it in GitHub Desktop.
Save antife-yinyue/86b0bfcde44bec798e2d to your computer and use it in GitHub Desktop.
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, function listener(event){
resolve(event)
this.removeEventListener(event, listener, useCapture);
},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