I have two promise methods, first one is GetInitialData
which would run only once, also an Int array of 10 id called ids
and second method GetStudentName
which would be executed on each student id. Now I would like to combine all 11 methods (method 1 + 10 * method 2) in Promise.All, how could I write the code which would combine the GetInitialData
along with 10 instances of GetStudentName
into an array inside Promise.All, something like below?
Promise.All([GetInitialData + IDs.map(Id => GetStudentName(Id)]);
you are on the right path:
Promise.all([
getInitialData,
// you need to spread this one as it is an array of promises:
...ids.map(id => getStudentName(id),
]);
Here is a demo:
all async functions are replaced with promises that resolves within a random time
const fnPromise = () => new Promise((resolve, reject) =>
setTimeout(() => resolve(), Math.round(Math.random() * 1000))
);
let i = 0;
async function getInitialData() {
await fnPromise();
return i++;
}
async function getStudentName() {
await fnPromise();
return i++;
}
const ids = [1, 2, 3, 4, 5, 6];
async function init() {
$("#console").html('Please wait...');
const allResolved = await Promise.all([
getInitialData(),
...ids.map(() => getStudentName()),
]);
// console.log(JSON.stringify(allResolved, null, 2))
$("#console").html(`[${allResolved.join(', ')}]`)
}
init()
body {
background: #333;
color: #fff;
font-size:2rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre id='console'></pre>