一个Promise的简单实现 发表于 2016-03-16 | 分类于 web 什么是Promise Promise就是抽象异步处理对象以及对其进行各种操作的组件。比较土的说法就是,提高多从回调带来的代码可阅读性。 一个简单的实现:123456789101112131415161718192021222324252627282930313233343536373839404142434445function Promise() { this.callbacks = [];}Promise.prototype = { constructor: Promise, resolve: function(result) { this.complete('resolve', result); }, reject: function(result) { this.complete('reject', result); }, complete: function(type, result) { while(this.callbacks[0]) { this.callbacks.shift()[type](result); } }, then: function(successHandle, errorHandle) { this.callbacks.push({ resolve: successHandle, reject: errorHandle }); }};//使用var promise = new Promise();var delay1 = function() { setTimeout(function() { promise.resolve('hello world'); }, 1000); return promise;}delay1() .then(function(re) { var re = re + ' Angular'; console.log(re); promise.resolve(re); });