PromiseConstructor.js [plain text]
function all(iterable)
{
"use strict";
if (!@isObject(this))
@throwTypeError("|this| is not a object");
var promiseCapability = @newPromiseCapability(this);
var values = [];
var index = 0;
var remainingElementsCount = 1;
function newResolveElement(index)
{
var alreadyCalled = false;
return function (argument)
{
if (alreadyCalled)
return @undefined;
alreadyCalled = true;
@putByValDirect(values, index, argument);
--remainingElementsCount;
if (remainingElementsCount === 0)
return promiseCapability.@resolve.@call(@undefined, values);
return @undefined;
}
}
try {
for (var value of iterable) {
@putByValDirect(values, index, @undefined);
var nextPromise = this.resolve(value);
var resolveElement = newResolveElement(index);
++remainingElementsCount;
nextPromise.then(resolveElement, promiseCapability.@reject);
++index;
}
--remainingElementsCount;
if (remainingElementsCount === 0)
promiseCapability.@resolve.@call(@undefined, values);
} catch (error) {
promiseCapability.@reject.@call(@undefined, error);
}
return promiseCapability.@promise;
}
function race(iterable)
{
"use strict";
if (!@isObject(this))
@throwTypeError("|this| is not a object");
var promiseCapability = @newPromiseCapability(this);
try {
for (var value of iterable) {
var nextPromise = this.resolve(value);
nextPromise.then(promiseCapability.@resolve, promiseCapability.@reject);
}
} catch (error) {
promiseCapability.@reject.@call(@undefined, error);
}
return promiseCapability.@promise;
}
function reject(reason)
{
"use strict";
if (!@isObject(this))
@throwTypeError("|this| is not a object");
var promiseCapability = @newPromiseCapability(this);
promiseCapability.@reject.@call(@undefined, reason);
return promiseCapability.@promise;
}
function resolve(value)
{
"use strict";
if (!@isObject(this))
@throwTypeError("|this| is not a object");
if (@isPromise(value)) {
var valueConstructor = value.constructor;
if (valueConstructor === this)
return value;
}
var promiseCapability = @newPromiseCapability(this);
promiseCapability.@resolve.@call(@undefined, value);
return promiseCapability.@promise;
}