DEV Community

chandra penugonda
chandra penugonda

Posted on

Using Promise.all,Implement mapLimit async function

Implement a mapLimit function that is similar to the Array.map() which returns a promise that resolves on the list of output by mapping each input through an asynchronous iteratee function or rejects it if any error occurs. It also accepts a limit to decide how many operations can occur at a time.

The asynchronous iteratee function will accept a input and a callback. The callback function will be called when the input is finished processing, the first argument of the callback will be the error flag and the second will be the result.

Solution:

function getNameById(id, callback) {
  // simulating async request
  const randomRequestTime = Math.floor(Math.random() * 100) + 200;

  setTimeout(() => {
    callback(id === 3 ? true : false, "User" + id);
  }, randomRequestTime);
}

function mapLimit(arr, limit, iterator, cb) {
  return new Promise((resolve) => {
    const output = [];
    let startIndex = 0;
    while (startIndex < arr.length) {
      const slicedArr = arr.slice(startIndex, startIndex + limit);
      startIndex += limit;
      output.push(
        Promise.allSettled(
          slicedArr.map((item) => {
            return new Promise((resolve, reject) => {
              iterator(item, (err, result) => {
                if (err) {
                  reject(err);
                } else {
                  resolve(result);
                }
              });
            });
          })
        )
      );
    }
    return resolve(Promise.all(output));
  });
}

let numPromise = mapLimit([1, 2, 3, 4, 5], 3, getNameById, (result) => {
  console.log(result);
});

numPromise
  .then((result) => console.log("success:", result[0], result[1]))
  .catch(() => console.log("no success"));

Enter fullscreen mode Exit fullscreen mode

Credits: https://learnersbucket.com/examples/interview/implement-maplimit-async-function/

Top comments (0)