提交 244d7113 编写于 作者: J Johannes Rieken

debt - fix sync-then-behaviour in polyfill-promise

上级 913e891c
......@@ -42,14 +42,14 @@ export class PolyfillPromise<T = any> implements Promise<T> {
constructor(winjsPromise: WinJSPromise);
constructor(callback: (resolve: (value?: T) => void, reject: (err?: any) => void) => any);
constructor(callback: WinJSPromise | ((resolve: (value?: T) => void, reject: (err?: any) => void) => any)) {
constructor(initOrPromise: WinJSPromise | ((resolve: (value?: T) => void, reject: (err?: any) => void) => any)) {
if (WinJSPromise.is(callback)) {
this._winjsPromise = callback;
if (WinJSPromise.is(initOrPromise)) {
this._winjsPromise = initOrPromise;
} else {
this._winjsPromise = new WinJSPromise((resolve, reject) => {
let initializing = true;
callback(function (value) {
initOrPromise(function (value) {
if (!initializing) {
resolve(value);
} else {
......@@ -68,10 +68,28 @@ export class PolyfillPromise<T = any> implements Promise<T> {
}
then(onFulfilled?: any, onRejected?: any): PolyfillPromise {
return new PolyfillPromise(this._winjsPromise.then(onFulfilled, onRejected));
let sync = true;
let promise = new PolyfillPromise(this._winjsPromise.then(
onFulfilled && function (value) {
if (!sync) {
onFulfilled(value);
} else {
setImmediate(onFulfilled, value);
}
},
onRejected && function (err) {
if (!sync) {
onFulfilled(err);
} else {
setImmediate(onFulfilled, err);
}
}
));
sync = false;
return promise;
}
catch(onRejected?: any): PolyfillPromise {
return new PolyfillPromise(this._winjsPromise.then(null, onRejected));
return this.then(null, onRejected);
}
}
......@@ -51,6 +51,33 @@ suite('Polyfill Promise', function () {
});
});
test('sync-then, NativePromise', function () {
const actual: string[] = [];
const promise = Promise.resolve(123).then(() => actual.push('inThen'));
actual.push('afterThen');
return promise.then(() => {
assert.deepEqual(actual, ['afterThen', 'inThen']);
});
});
test('sync-then, WinJSPromise', function () {
const actual: string[] = [];
const promise = WinJSPromise.as(123).then(() => actual.push('inThen'));
actual.push('afterThen');
return promise.then(() => {
assert.deepEqual(actual, ['inThen', 'afterThen']);
});
});
test('sync-then, PolyfillPromise', function () {
const actual: string[] = [];
const promise = PolyfillPromise.resolve(123).then(() => actual.push('inThen'));
actual.push('afterThen');
return promise.then(() => {
assert.deepEqual(actual, ['afterThen', 'inThen']);
});
});
test('PolyfillPromise, executor has two params', function () {
return new PolyfillPromise(function () {
assert.equal(arguments.length, 2);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册