Promises

From CommonJS Spec Wiki
Jump to: navigation, search

STATUS: PROPOSAL, DISCUSSION

Contents

Promises

Promises provide a well-defined interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time. By utilizing a standard interface, different components can return promises for asynchronous actions and consumers can utilize the promises in a predictable manner. Promises can also provide the fundamental entity to be leveraged for more syntactically convenient language-level extensions that assist with asynchronicity.

Prior Art

Proposals

Requirements

function API(input) {
    return when(input, function (input) {
    });
};

For example, a password checking API must be able to retain a reference to a remote table of password hashes and must never give the consumer direct access to any of those hashes.

function PasswordChecker(accounts) {
    return function (user, password) {
        var passwordHash = Q.get(accounts, user);
        return when(passwordHash, function (passwordHash) {
            if (hash(password) === passwordHash)
                return true;
        };
    };
}
// returns a password checking capability
// but does not return access to the passwordHash
return PasswordChecker(accounts);
var internalCounter = 0;

// /!\ HAZARD: untrusted promise given direct access to a
// function that has the capability to alter internal
// state, either during the same turn or in any future turn
promise("when", function () {
    internalCounter++;
});

// /!\ HAZARD: untrusted promise given direct access to a
// function that has the capability to alter internal
// state, either during the same turn or in any future turn
promise.when(function () {
    internalCounter++;
});

// /!\ HAZARD: untrusted promise given direct access to a
// function that has the capability to alter internal
// state, either during the same turn or in any future turn
promise.then(function () {
    internalCounter++;
});

ASSERT.equal(internalCounter, 0);
// /!\ HAZARD: untrusted promise given direct access to a
// function that has the capability to alter internal
// state, either during the same turn or in any future turn
var internalCounter = 0;
when(promise, function () {
    internalCounter++;
});
ASSERT.equal(internalCounter, 0);
var internalCounter = 0;
when(promise, function (value) {
    internalCounter++;
}, function (error) {
    internalCounter++;
});
setTimeout(function () {
    ASSERT.ok(internalCounter == 0 || internalCounter == 1);
}, forever);


Related Discussions

Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox