UNPKG

q

Version:

A library for promises (CommonJS/Promises/A,B,D)

33 lines (31 loc) 1.06 kB
A 125 byte (<140 byte) promise library for JavaScript. defer = function ( pending, // local: array of callbacks to notify value // local: resolution value of the promise ) { pending = []; // [...] (truthy) if unresolved, // 0 (falsy) if resolved return { resolve: function (_value) { // store the resolution value (which may be any // value including falsy values) value = _value; // call all callbacks with the value while (pending.length) pending.shift()(value); // change state to "resolved" pending = 0; }, then: function (callback) { // if not yet resolved, store callback and call // when a resolution value is available if (pending) { pending.push(callback); // if resolved, call callback with resolution // value immediately } else { callback(value); } } }; };