Sallar Kaboli / Exploring JavaScript & Things.


I like Javascript Promises a lot, so I’m trying to fit them everywhere in my apps. If you haven’t heard about Promises, or haven’t used them yet, I suggest you check out this great guide on them.

I also like ES5 array functions and in my opinion they’re a few of the best additions to the language. My favorites are filter and map. The problem with these functions is they are synchronous, and I find myself trying to do something like this:

  1. var result = arr.map(function(item) {
  2. // Do something Async here.
  3. });

Which clearly isn’t going to work out since the callback function passed to map needs to have a return value. A possible solution to this is turn each array item into a Promise object and wait for all promises to resolve using Promise.all. Something like:

  1. var arr = [1, 2, 3];
  2. var promisified = arr.map(function(item) {
  3. return new Promise(function(resolve) {
  4. resolve(item * 10);
  5. });
  6. });
  7. Promise.all(promisified).then(function(result) {
  8. console.log(result); // [10, 20, 30];
  9. });

This solution is alright, until you need to do it repeatedly then it will get verbose pretty fast. So I made a small helper library to do it.

promise-arrays

This super small library provides async versions of map and filter which return a Promise with the result. Take this example:

  1. var PromiseArrays = require('promise-arrays');
  2. var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  3. PromiseArrays.filter(arr, function(item) {
  4. return new Promise(function(resolve) {
  5. window.setTimeout(function() {
  6. resolve(item > 3 && item < 8);
  7. }, 100);
  8. });
  9. }).then(function(result) {
  10. console.log(result); // [4, 5, 6, 7] after about ~100ms.
  11. });

It’s possible to return a new Promise or a normal value from the callback.

promise-arrays is available to use with Node.JS, UMD and browser globals. Check it out on Github and please report any issues. All suggestions are also welcome :-)


tags: Javascript ،  Promise