Concept - Distilling how a promise works?
javascript
Solution
Can someone implement the most basic promise in a few lines?
Here it is:
function Promise(exec) {
// takes a function as an argument that gets the fullfiller
var callbacks = [], result;
exec(function fulfill() {
if (result) return;
result = arguments;
for (let c;c=callbacks.shift();)
c.apply(null, arguments);
});
this.addCallback = function(c) {
if (result)
c.apply(null, result)
else
callbacks.push(c);
}
}
Additional `then` with chaining (which you will need for the answer):
Promise.prototype.then = function(fn) {
return new Promise(fulfill => {
this.addCallback((...args) => {
const result = fn(...args);
if (result instanceof Promise)
result.addCallback(fulfill);
else
fulfill(result);
});
});
};
Disclaimer: the code is lacking error handling (an error state, providing a `reject` function, and using `try`/`catch` around `exec(…)` and `fn(…)`), doing recursive `resolve(…)` instead of `fulfill(…)` (for thenables), and guaranteed consistent asynchrony (of `then` callbacks) - but adding those does not really change the basic concept.
How are these two snippets related?
`ajax` is called from the `getPromiseForAjaxResult` function:
function getPromiseForAjaxResult(ressource) {
return new Promise(function(callback) {
ajax({url:ressource}, callback);
});
}
Problem
I've looked at many implementations and they all look so different I can't really distill what the essence of a promise is. If I had to guess it is just a function that runs when a callback fires. Can someone implement the most basic promise in a few lines of code w/ out chaining. For example from this answer Snippet 1 ``` var a1 = getPromiseForAjaxResult(ressource1url); a1.then(function(res) { append(res); return a2; }); ``` How does the function passed to `then` know when to run. That is, how is it passed back to the callback code that ajax fires on completion. Snippet 2 ``` // generic ajax call with configuration information and callback function ajax(config_info, function() { // ajax completed, callback is firing. }); ``` How are these two snippets related? Guess: ``` // how to implement this (function () { var publik = {}; _private; publik.then = function(func){ _private = func; }; publik.getPromise = function(func){ // ?? }; // ?? }()) ```