With the new features of ES5 we can build async functions quickly.
Spoiler: Unfortunately, by the language design, the async
and await
keywords on JS functions actually don't allow us to do tasks at the same time with multi-threads like the name sound's, actually is the opposite, so we are able to resolve a task and then go to another task. Is more to a Synchronous way.
Let's code!!
First we need to create the function that we need to wait
for, this function will check if the number is odd or even, here we can have many possibilities, the point here is to have a Promise function, like we have in the http requests, that wait's for a response from the API.
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`);
});
}
At the traditional way, the 'Promise' will be executed, and we get the 'response' value from the Promise
by using the 'then' method, imagine that can turn in a infinite cascade if we have a Promise
that return's a new Promise
.
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 hard, depending on the size of the code.
allNumbersAreOdd(1, 2); // "the number 2 is even"
allNumbersAreOdd(1, 1); // "all numbers are odd"
Using the async feature, we are able to add the keyword await
in front of the async
functions ( a http request for example or the promise that we create above which is async
), and that allow us to wait for the response of the function before proceed, and using that along with the try & catch
we can do the error treatment easily.
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"
Top comments (0)