Is there a human-readable was polifil of promis on collbato?

I in order to better understand the structure of the promis
April 3rd 20 at 17:13
3 answers
April 3rd 20 at 17:15
Solution
April 3rd 20 at 17:17
Solution
Once for itself wrote, that would be to understand how about working under the hood. I think the main message will be clear. Written specifically for es5.
promise.js
;(function () {
 'use strict';

 var cache = {};

 var promise = function (handler) {
 var uuid = Number(String(Math.random()).slice(2)).toString(32);

 cache[uuid] = {
 then: [],
 catch: []
};

 var api = {
 status: {
 pending: true
 resolved: false,
 rejected: false
},

 queue: function (items, callback) {
 var ready = promise();
 var collection = [];
 (function next(index) {
 var item = callback(items[index], index, items);
 if (!item) return;
 item.then(function (data) {
 collection[index] = data;
 items[index + 1] ? next(index + 1) : ready.resolve(collection);
});
}(0));
 return ready;
},

 parallel: function (items, callback) {
 var ready = promise();
 var collection = [];
 var counter = 0;
 for (var i = 0; i < items.length; i++) {
 (function (index) {
 var item = callback(items[index], index, items);
 if (!item) return;
 item.then(function (data) {
counter++;
 collection[index] = data;
 if (items.length === counter) {
ready.resolve(collection);
}
});
}(i));
}
 return ready;
},

 all: function (promises) {
 var ready = promise();
 var collection = [];
 var counter = 0;
 for (var i = 0; i < promises.length; i++) {
 (function (index) {
 promises[index].then(function (data) {
counter++;
 collection[index] = data;
 if (promises.length === counter) {
ready.resolve(collection);
}
});
}(i));
}
 return ready;
},

 then: function (callback, data) {
 if (api.status.resolved) {
callback(data);
 } else {
cache[uuid].then.push(callback);
}
 return api;
},

 catch: function (callback, data) {
 if (api.status.rejected) {
callback(data);
 } else {
cache[uuid].catch.push(callback);
}
 return api;
},

 resolve: function (data) {
 if (api.status.resolved) return api;
 api.status.pending = false;
 api.status.resolved = true;
 for (var i = 0; i < cache[uuid].then.length; i++) {
 api.then(cache[uuid].then[i], data);
}
 return api;
},

 reject: function (data) {
 if (api.status.rejected) return api;
 api.status.pending = false;
 api.status.rejected = true;
 for (var i = 0; i < cache[uuid].catch.length; i++) {
 api.catch(cache[uuid].catch[i], data);
}
 return api;
}
};

 if (handler) {
 var instanse = promise();
 handler(instanse.resolve instanse.reject);
 return instanse;
 } else {
 return api;
}
};

 window.promise = promise;

}());


And code examples:
promise.examples.js
(function () {
 'use strict';

 /** Single AJAX request */
 ajax('https://jsonplaceholder.typicode.com/posts/1').then(function (posts) {
console.log(posts);
});

 /** Parallel AJAX requests */
 promise().parallel([1, 2, 3, 4, 5, 6], function (id) {
 return ajax(`https://jsonplaceholder.typicode.com/posts/${id}`);
 }).then(function (posts) {
console.log(posts);
});

 /** Sequential AJAX requests */
 promise().queue([1, 2, 3, 4, 5, 6], function (id) {
 return ajax(`https://jsonplaceholder.typicode.com/posts/${id}`);
 }).then(function (posts) {
console.log(posts);
});

 /** The use of promise. Example 1 - callback function */
 getPostsMeta().then(function (posts) {
console.log(posts);
});

 getPostsMeta function() {
 return promise(function (resolve, reject) {
 ajax('https://jsonplaceholder.typicode.com/posts').then(function (posts) {
 var result = posts.map(function (post) {
 return {
 userId: post.userId
 postId: post.id
};
});
 return resolve (result);
 }).catch(function (error) {
 return reject(error);
});
});
}

 /** The use of promise. Example 2 - creating instance */
 wait(800).then(function (time) {
 console.log(`Success async wait for ${time}ms`);
});

 /** The version with async/await */
 (async () => {
 const time = await wait(800);
 console.log(`Success async wait for ${time}ms`);
})();

 function wait(time) {
 return promise(function (resolve) {
 setTimeout(function () {
resolve(time);
 }, time);
});
}

 /** Async/Await with a Thenable object */
 (async () => {
 var users = await ajax('https://jsonplaceholder.typicode.com/users');
console.log(users);
})();

 /** Callback fulfillment of all promises */
 var promises = [wait(500), wait(2500), wait(1000), wait(800)];
 promise().all(promises).then(function (timers) {
 console.log('All finished timers', timers);
});

 // --------------------------------------------------------------------
 ajax function(link) {
 var ready = promise();
 var xhr = new XMLHttpRequest();
 xhr.onload = function () {
 if (xhr.status >= 200 & xhr.status < 400) {
 var data = tryCatch(function () {
 return JSON.parse(xhr.responseText);
 }, xhr.responseText);
ready.resolve(data);
 } else {
 var error = {
 status: xhr.status
 error: xhr.statusText
};
ready.reject(error);
}
};
 xhr.onerror = function () {
 var error = {
 status: xhr.status
 error: xhr.statusText
};
ready.reject(error);
};
 xhr.open('GET', link, true);
xhr.send();
 return ready;
}

 function tryCatch(done, fail) {
 try {
 if (typeof done === 'function') {
 return done();
}
 } catch (error) {
 if (fail !== undefined) {
 if (typeof fail === 'function') {
 return fail(error);
 } else {
 return fail;
}
}
}
}

}());
April 3rd 20 at 17:19
Note the async/await.
While some are switching from the use of Kabakov on promises, others have promoted with promises for async/await.
With promises the error processing - Keny commented on April 3rd 20 at 17:22
And wait until you earn at least in all major browsers - ambrose.Simonis commented on April 3rd 20 at 17:25
@ambrose.Simonis, In all major and how it works. Problems only marginal ie, you can transpalet Babel. - Hayley.Zemlak commented on April 3rd 20 at 17:28
@Hayley.Zemlak, Your truth. - ambrose.Simonis commented on April 3rd 20 at 17:31
@Keny, someone like that. Async/await allow you to write in a synchronous style, and handle errors the usual try..catch. In my opinion, it is more convenient. - Hayley.Zemlak commented on April 3rd 20 at 17:34
Duck well nobody forbids to use Babel. - buck72 commented on April 3rd 20 at 17:37
@Hayley.Zemlak, here I also prefer to work with konstrukcjami try catch error handling. So the obvious than in .then/.catch or kolbeco. - buck72 commented on April 3rd 20 at 17:40
@buck72in a try catch block can be many functions and from which came the error is not clear.
If each function individually wrapped in a try catch, the code becomes clogged. - Keny commented on April 3rd 20 at 17:43

Find more questions by tags JavaScript