Created
July 8, 2022 15:14
-
-
Save timgarciaa/5f7a7325bd193dcf2726fe7575fc4dac to your computer and use it in GitHub Desktop.
Mapping example with async
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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