Reputation: 5274
I need to perform a GET
request to an API multiple times in a function. I then need to handle all the responses as a whole once they have all yielded responses. What is the best JS design to do this?
edit: I originally asked for a Promise.all()
polyfill. But I feel like I don't need all the functionality of promises and looking for a simpler solution.
I basically need Promise.all(iterable);
functionailty in native JS.
Upvotes: 1
Views: 44
Reputation: 23798
This is a polyfill for Promise.all
Promise.all = function (arr) {
var args = Array.prototype.slice.call(arr);
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([]);
var remaining = args.length;
function res(i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then;
if (typeof then === 'function') {
then.call(val, function (val) {
res(i, val);
}, reject);
return;
}
}
args[i] = val;
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex);
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i]);
}
});
};
This code is a part of this library.
Upvotes: 3