Using await PromiseAll to resolve faster multiple responses

author
0 minutes, 52 seconds Read
const users = {
  1: {
    name: "Alan",
    age: 25
  },
  2: {
    name: "Lisa",
    age: 27
  },
  3: {
    name: "George",
    age: 32
  },
  4: {
    name: "Ann",
    age: 23
  }
};
const usersIds = [1, 2, 3, 4];


const searchUser = (id) => { // search the main object based on ids
  const user = users[id];

  return new Promise((resolve, reject) => {
    if (user) {
      setTimeout(() => resolve(user), 1000);
    } else {
      reject(`There is no user with the given id ${id}`);
    }
  });
};

const userListSlow = async () => {
  const usersArr = [];

  // This way we will need 1 sec per response
  // As we're receiving the response serielized
  for (const id of usersIds) {
    const user = await searchUser(id); // Try to avoid using await inside loops
    usersArr.push(user);
  }
  return usersArr;
};

const userListFast = async () => {
  const usersArr = [];

  // This way we resolve each promise at same time 
  // So it takes 1 sec to get them all
  for (const id of usersIds) {
    usersArr.push(searchUser(id));
  }
  return await Promise.all(usersArr);
};

const userListFastv2 = async () => {
  // More elegant version of userListFast function
  return await Promise.all(usersIds.map(searchUser));
};

const initSlow = () => {
  console.time("awaitSlow");
  userListSlow().then((users) => {
    console.table(users);
    console.timeEnd("awaitSlow");
  });
};

const initFast = () => {
  console.time("awaitFast");
  userListFast().then((users) => {
    console.table(users);
    console.timeEnd("awaitFast");
  });
};

initSlow();
initFast();

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *