loading...
Cover image for Go make async functions, 
it's easier than it looks

Go make async functions, it's easier than it looks

mmatheuspalma profile image Matheus Palma Updated on ・1 min read

With the new features of ES5 we can build async functions quickly;

Let's code

First, we build an promise, this promise will check if number is odd

const isOdd = (value) => {
  return new Promise((resolve, reject) => {
    const isOdd = value % 2 !== 0;

    (isOdd)
      ? resolve(`the number ${value} is odd`)
      : reject(`the number ${value} is even`);
  });
} 

The 'promise' will be executed, and we need to get the 'response'

const allNumbersAreOdd = (number1, number2) => {
  isOdd(number1).then(response => {
    isOdd(number2).then(response => {
      console.log('all numbers are odd');
    }).catch(error => {
      console.log(error);
    });
  }).catch(error => {
    console.log(error);
  });
}

So doing maintenance can be difficult, depending on the size of the code

allNumbersAreOdd(1, 2); // "the number 2 is even"
allNumbersAreOdd(1, 1); // "all numbers are odd"

With async function

async const numberIsOdd = (number) => {
  try {
    const numberIsOdd = await isOdd(number);

    console.log(numberIsOdd);
  } catch (error) {
    console.log(error);
  }  
}
numberIsOdd(5) // "the number 5 is odd"

If we need call more than one promises, is easy
do maintenance compared to the traditional way, because we can treat the errors in the same function

async const allNumbersAreOdd = (number1, number2) => {
  try {
    await isOdd(number1);
    await isOdd(number2);

    console.log('all numbers are odd');
  } catch (error) {
    console.log(error);
  }  
}
allNumbersAreOdd(1, 2); // "the number 2 is even"
allNumbersAreOdd(1, 1); // "all numbers are odd"

Posted on by:

mmatheuspalma profile

Matheus Palma

@mmatheuspalma

I'm software engineer focused in javascript

Discussion

markdown guide