Promises are about making asynchronous code retain most of the lost properties of synchronous code such as flat indentation and one exception channel. – Bluebird Wiki: Promise Anti Patterns
Promises 是为了让异步代码也能保持这些同步代码的属性:扁平缩进和单异常管道。
Deferred 反模式
这种反模式中,deferred
对象的创建是没有意义的,反而会增加代码的复杂度。
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
//Code copyright by Twisternha http://stackoverflow.com/a/19486699/995876 CC BY-SA 2.5 myApp.factory('Configurations', function (Restangular, MotorRestangular, $q) { var getConfigurations = function () { var deferred = $q.defer(); MotorRestangular.all('Motors').getList().then(function (Motors) { //Group by Config var g = _.groupBy(Motors, 'configuration'); //Map values var mapped = _.map(g, function (m) { return { id: m[0].configuration, configuration: m[0].configuration, sizes: _.map(m, function (a) { return a.sizeMm }) } }); deferred.resolve(mapped); }); return deferred.promise; }; return { config: getConfigurations() } }); |
这里的 deferred
对象并没有什么意义,而且可能在出错的情况下无法捕获。
正确的写法应该为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
myApp.factory('Configurations', function (Restangular, MotorRestangular, $q) { var getConfigurations = function () { //Just return the promise we already have! return MotorRestangular.all('Motors').getList().then(function (Motors) { //Group by Cofig var g = _.groupBy(Motors, 'configuration'); //Return the mapped array as the value of this promise return _.map(g, function (m) { return { id: m[0].configuration, configuration: m[0].configuration, sizes: _.map(m, function (a) { return a.sizeMm }) } }); }); }; return { config: getConfigurations() } }); |
再举一个例子:
1 2 3 4 5 6 7 8 9 10 11 |
function applicationFunction(arg1) function applicationFunction(arg1) Deferred 反模式这种反模式中, 例如:
这里的 正确的写法应该为:
再举一个例子:
|