///////////////////////
// 定义promise.js
///////////////////////
var Promise = function(fn) {
var state = 'pending';
var doneList = [];
var catcher = null;
this.then = function(done) {
switch (state) {
case 'pending':
doneList.push(done);
return this;
default:
break;
}
};
this.catch = function(c) {
switch (state) {
case 'pending':
catcher = c;
break;
default:
break;
}
};
function resolve(newValue) {
setTimeout(function() {
state = 'fulfilled';
var value = newValue;
doneList.forEach(function(fulfill) {
value = fulfill(value);
});
}, 0);
}
function reject(e) {
setTimeout(function() {
state = 'rejected';
catcher && catcher(e);
}, 0);
}
fn(resolve, reject);
};
///////////////////////
// 使用
///////////////////////
<script src="libs/promise.js"></script>
...
new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('ok');
}, 1000);
}).then(function (res) {
console.log(res);
}).catch(function (err) {
console.log(err);
});