Skip to content

Instantly share code, notes, and snippets.

@timgarciaa
Created July 8, 2022 15:14
Show Gist options
  • Save timgarciaa/5f7a7325bd193dcf2726fe7575fc4dac to your computer and use it in GitHub Desktop.
Save timgarciaa/5f7a7325bd193dcf2726fe7575fc4dac to your computer and use it in GitHub Desktop.
Mapping example with async
var async = require("async");
var fruits = ["apple", "mango", "orange", "grapes"];
const myAsyncMapping = async (fruits) => {
var num = 1;
var fruitObject = fruits.map((fruit) => {
// this will produce an error
var numberedFruit = await assignNumber(num, fruit);
return numberedFruit;
});
return fruitObject;
};
const myAsyncForLoop = async (fruits) => {
var fruitObject = [];
for (var x=0; x < fruits.length; x++) {
fruitObject.push(await assignNumber(x+1, fruits[x]));
}
return fruitObject;
};
async function assignNumber(num, fruit) {
return new Promise((resolve) => {
setTimeout(() => {
console.log('num ' + num + ' fruit ' + fruit);
var numberedFruit = {};
numberedFruit.number = num++;
numberedFruit.fruit = fruit;
resolve(numberedFruit);
}, 2000);
});
}
async function run() {
console.log(await myAsyncMapping(fruits));
console.log(await myAsyncForLoop(fruits));
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment