Last active
January 4, 2022 01:45
-
-
Save wintercn/97a8df0f3cec6967f499 to your computer and use it in GitHub Desktop.
一组小清新的promise风格小函数
This file contains 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); | |
}) | |
} |
@VinnSung 满足你了
为啥不混一些VS风格的函数大括号?
post 没有 setRequestHeader content-type 嘛,差评!
还有 response code 2xx 应该都是 resolve 滴。
waitFor 后没有 remove listener。。。
encodeURIComponenet 拼错了吧
有些参数分隔逗号后面没有空格……好想空格……
咋办,上面吐槽的都差不多了……
304不兼容一发?
winter竟然是男的! 这个吐槽如何!
学习
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
有些 function 后面的花括号没有空格……好想空格