Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 6936a37

Browse files
committed
perf($q): reduce closures when resolving promises
- changes Deferred.$$resolve to only wrap the internal resolve/reject when wrapping another promise
1 parent 63a834d commit 6936a37

File tree

1 file changed

+34
-24
lines changed

1 file changed

+34
-24
lines changed

src/ng/q.js

+34-24
Original file line numberDiff line numberDiff line change
@@ -243,18 +243,6 @@ function $$QProvider() {
243243
*/
244244
function qFactory(nextTick, exceptionHandler) {
245245
var $qMinErr = minErr('$q', TypeError);
246-
function callOnce(self, resolveFn, rejectFn) {
247-
var called = false;
248-
function wrap(fn) {
249-
return function(value) {
250-
if (called) return;
251-
called = true;
252-
fn.call(self, value);
253-
};
254-
}
255-
256-
return [wrap(resolveFn), wrap(rejectFn)];
257-
}
258246

259247
/**
260248
* @ngdoc method
@@ -362,23 +350,45 @@ function qFactory(nextTick, exceptionHandler) {
362350
},
363351

364352
$$resolve: function(val) {
365-
var then, fns;
353+
var then;
354+
try {
355+
then = (isObject(val) || isFunction(val)) && isFunction(then = val.then) ? then : false;
356+
} catch (e) {
357+
this.$$reject(e);
358+
exceptionHandler(e);
359+
return;
360+
}
366361

367-
fns = callOnce(this, this.$$resolve, this.$$reject);
362+
if (then) {
363+
this.promise.$$state.status = -1;
364+
this.$$delayResolve(val, then);
365+
} else {
366+
this.promise.$$state.value = val;
367+
this.promise.$$state.status = 1;
368+
scheduleProcessQueue(this.promise.$$state);
369+
}
370+
},
371+
372+
$$delayResolve: function(promiseLike, then) {
373+
var that = this;
374+
var done = false;
368375
try {
369-
if ((isObject(val) || isFunction(val))) then = val && val.then;
370-
if (isFunction(then)) {
371-
this.promise.$$state.status = -1;
372-
then.call(val, fns[0], fns[1], simpleBind(this, this.notify));
373-
} else {
374-
this.promise.$$state.value = val;
375-
this.promise.$$state.status = 1;
376-
scheduleProcessQueue(this.promise.$$state);
377-
}
376+
then.call(promiseLike, resolvePromise, rejectPromise, simpleBind(this, this.notify));
378377
} catch (e) {
379-
fns[1](e);
378+
rejectPromise(e);
380379
exceptionHandler(e);
381380
}
381+
382+
function resolvePromise(val) {
383+
if (done) return;
384+
done = true;
385+
that.$$resolve(val);
386+
}
387+
function rejectPromise(val) {
388+
if (done) return;
389+
done = true;
390+
that.$$reject(val);
391+
}
382392
},
383393

384394
reject: function(reason) {

0 commit comments

Comments
 (0)