简体   繁体   中英

JavaScript ES6 - How to combine promise methods in Promise.All?

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>

const getOne = async () => 1; const getTwo = async () => 2; (async () => { const [one, two] = await Promise.all([getOne(), getTwo()]); console.log(one); console.log(two); })().then(undefined); // 1 // 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM