Last active
January 4, 2022 01:45
-
-
Save wintercn/97a8df0f3cec6967f499 to your computer and use it in GitHub Desktop.
一组小清新的promise风格小函数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
学习