JS&TS
May 18, 2024
Async map in JS
Here we'll discuss about async map in JS and how does create it?
Simetimes we need to map values from an array of promises
. Fortunetly we can write our own implementation:
if (!Promise.map) { Promise.map = function(vals = [], cb = null) { return Promise.all(vals.map(function(val) { return new Promise(function(resolve) { cb(val, resolve); }); })); } } var p1 = Promise.resolve(12); var p2 = Promise.resolve(24); var p3 = Promise.resolve('Oops'); Promise.map([p1, p2, p3], function(pr, done) { Promise.resolve(pr) .then(function(v) { return done(v * 2); }, done); }).then(function(vals) { console.log(vals) }); // [24, 48, 'Oops']
Conclusion:
Js has mechanism for adding your own implementation and that means if want use a feature which hasn't implement yet, you'll need add your own polyfill for that.