DEV Community

Discussion on: Promises or async/await, Which Is Better?

Collapse
 
peerreynders profile image
peerreynders

you should mostly use async/await, but in some cases, it's OK to use promises.

The Catch 22 is: how does one become competent with promises if one predominantly uses async/await?

async/await accommodates a synchronous mindset leaving everybody in their comfort zone while promises require a shift in thinking - breaking processing into (micro)tasks ("Many of us are using promises without really understanding them", 2015; The Event Loop, 2018).

Exploiting opportunities for concurrent asynchronous execution is possible in async/await with Promise.all() and Promise.allSettled() but a synchronous mindset isn't exactly honed towards recognizing these type of opportunities.

Also before async/await I always found it clearer to use function declarations instead of inline anonymous function expressions.

import axios from 'axios';

const reportInfo = (info) => console.log(infoToMessage(info));
const logError = (error) => console.log(errorToMessage(error));

fetchInfoByTitle('in quibusdam tempore odit est dolorem')
  .then(reportInfo) // 'Post (id: 12) with title "in quibusdam tempore odit est dolorem" has 5 comments.'
  .catch(logError);

function fetchInfoByTitle(title) {
  return axios
    .get('https://jsonplaceholder.typicode.com/posts')
    .then(fetchComments);

  function fetchComments(res) {
    const post = findPostByTitle(title, res.data);
    if (!post) return { title }; // nothing to do

    return axios
      .get(`https://jsonplaceholder.typicode.com/comments?postId=${post.id}`)
      .then(assembleInfo);

    function assembleInfo(res) {
      const comments = res.data;
      return {
        title,
        post,
        comments,
      };
    }
  }
}

function findPostByTitle(title, posts) {
  const findTitle = title.toLowerCase();
  return posts.find((p) => p.title.toLowerCase() === findTitle);
}

function infoToMessage(info) {
  if (!info.post) return `No post with a title of "${info.title}" found.`;

  const { post, comments } = info;
  const result = comments.length !== 1 ? `${comments.length} comments` : `1 comment`;
  return `Post (id: ${post.id}) with title "${post.title}" has ${result}.`;
}

function errorToMessage(error) {
  const url = error?.config?.url;
  return `Error: ${error.message}` + (url ? `; url: ${url}` : '');
}
Enter fullscreen mode Exit fullscreen mode