Skip to content

Instantly share code, notes, and snippets.

@chandu
Created April 29, 2021 14:41
Show Gist options
  • Save chandu/04e7f832abdf6c761b969c00b2373255 to your computer and use it in GitHub Desktop.
Save chandu/04e7f832abdf6c761b969c00b2373255 to your computer and use it in GitHub Desktop.
Ajax Ladi
const generatePromise = (valueGeneratorFn, delay = 1) => {
return new Promise((resolve) => {
setTimeout(() => resolve(valueGeneratorFn()), delay);
});
};
const getFirstDataSetAsync = async (input) => {
return generatePromise(() => input * 1);
};
const getSecondDataSetAsync = async (input) => {
return generatePromise(() => input * 2);
};
const getThirdDataSetAsync = async (input, repeatBy) => {
return generatePromise(() =>
Array(repeatBy).fill(input.toString()).join("~")
);
};
const generatePromisesForColumns = async (columns, repeatBy) => {
const colsPromises = columns.map((col) =>
getThirdDataSetAsync(col, repeatBy)
);
const result = await Promise.all(colsPromises);
return result;
};
const loadData = async (columns) => {
const sourceList = [1, 2, 3, 4, 5, 6];
const promises = sourceList
.map(async (input) => await getFirstDataSetAsync(input))
.map(async (valuePromise) => {
const value = await valuePromise;
const result = await getSecondDataSetAsync(value);
return result;
})
.map(async (valuePromise) => {
const value = await valuePromise;
return generatePromisesForColumns(columns, value);
});
return await Promise.all(promises).then((a) => {
const toReturn = a.reduce((acc, curr) => {
return acc.concat(curr);
}, []);
return toReturn;
});
};
module.exports = {
loadData,
};
const { loadData } = require("./ajax-ladi.js");
const run = async () => {
const result = await loadData([1, 2, 3, 4, 5]);
// result.forEach(console.log);
console.log(result);
console.log("Hola!");
};
(async () => {
await run();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment