JavaScript Snippet #0

Found an interesting javascript snippet:

1
2
3
4
const numbers = [1, 3, 5];
const addTwo = async (num) => num + 2;
const numbersPlusTwo = numbers.map(addTwo);
console.log(numbersPlusTwo);

Let’s digest it to understand what’s happening.

Line #1 is just defining an array with 3 elements.

Line #2 is defining an async function addTwo, so a call of this function will return a Promise object type.

async function
The async function declaration defines an asynchronous function, which returns an AsyncFunction object. An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.

When the map method on line #3 is called with the function addTwo as parameter, it will result in a new array with each element being a Promise object type.

Array.prototype.map
The map() method creates a new array with the results of calling a provided function on every element in the calling array.

The final result will be:

1
[ Promise { 3 }, Promise { 5 }, Promise { 7 } ]

PS: if we want to extract the value from each Promise object, I will add some code:

1
2
3
4
5
6
7
8
9
10
11
12
13
async function main() {
const numbers = [1, 3, 5];
const addTwo = async (num) => num + 2;
const numbersPlusTwo = await numbers.map(addTwo);
console.log(numbersPlusTwo);

for (let i in numbersPlusTwo) {
numbersPlusTwo[i] = await numbersPlusTwo[i];
}
console.log(numbersPlusTwo);
}

main();

returns:

1
2
[ Promise { 3 }, Promise { 5 }, Promise { 7 } ]
[ 3, 5, 7 ]
Ansible for the Absolute Beginner - Hands-On - DevOps Challenge-ul generației noastre

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×