„Execute functions in the following order using Promise chaining” 👨‍💻

Hi everyone in 2022! 🎉 This is my first article this year. Admittedly, it’s February right now, but I did a lot of other things during that time. It does not change the fact that I stopped writing new articles on my blog. 😎

In today’s article, I’ll show you the solution to one recruitment task that I recently had the opportunity to complete. The task is short but very interesting which tests your knowledge about asynchronicity issues in JavaScript.


1. Content of the task

First I would like to present to you the complete source code:

async function getIds() {
  return [1, 2, 3];
}

async function formatIds(ids) {
  return ids.map((id) => `item-${id}`);
}

async function uppercase(id) {
  return id.toUpperCase();
}

function processIds(ids) {
  /*
   * Fill the body of the function so it applies `uppercase` function above
   * to all elements of the `ids` array and returns this array.
   */
}

function printIds(ids) {
  console.log(ids.join(" "));
}

And here is the content of the task to be done based on this code:

Execute functions in the following order using Promise chaining:
1. getIds
2. formatIds
3. processIds
4. printIds

2. Solution of the task

Let’s start by editing the processIds() function first. This function is a part of asynchronous operation, so it should be properly preceded with async keyword.

We will use the map() function, because it returns an array, which in combination with the Promise.all() function will give us the expected result. The prepared function looks like this:

async function processIds(ids) {
  return Promise.all(ids.map(id => uppercase(id)));
}

We have the first part of the assignment written correctly and quite stylishly.
Now let’s do the second part of the task.

Enabling these functions can be done in 2 ways, the first is using standard syntax with the then() keyword:

getIds().then((ids) => {
  formatIds(ids).then((formattedIds) => {
    processIds(formattedIds).then((processedIds) => {
        printIds(processedIds);
      });
    });
});

Or we can use the newer syntax:

const ids = await getIds();
const formattedIds = await formatIds(ids);
const processedIds = await processIds(formattedIds);

printIds(processedIds);

The result will be the same every time:

'ITEM-1 ITEM-2 ITEM-3'

If you thought the same, congratulations on successfully completing the hiring process! ✅
How much would you like to earn at my company? 😄


You can also find this article on medium.com where I share my solutions to the problems I encountered during my software engineer career.

If you have additional questions, you can write to me on LinkedIn or Twitter.

Partners