<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>div{display:block;font-size: 2rem;}</style>
<body>
<h1>Promise兼容IE9</h1>
<div id="div"></div>
<script>
function NewPromise(fn) {
this.fn = fn;
this.fn(this.resolve.bind(this), this.reject.bind(this));
}
NewPromise.prototype.then = function(fn) {
fn = fn || new(Function);
this.then = fn;
return this;
};
NewPromise.prototype.catch = function(fn) {
fn = fn || new(Function);
this.catch = fn;
return this;
};
NewPromise.prototype.resolve = function(res) {
this.then(res);
}
NewPromise.prototype.reject = function(err) {
this.catch(err);
}
window.Promise = window.Promise || NewPromise;
var p = new Promise(function(res, rej) {
var timeOut = Math.floor(Math.random() * 2);
div.innerHTML += 'timeout: ' + timeOut + '<br>';
setTimeout(function () {
timeOut && (rej('超时了......'), 1) || res('200');
}, timeOut * 500);
}).then(function(res) {
div.innerHTML += '成功 ' + res +'<br>';
}).catch(function(err) {
div.innerHTML += '失败 ' + err +'<br>';
});
</script>
</body>
</html>
// 如果发现哪里有问题欢迎大家指教