繁体   English   中英

JavaScript ES6 - 如何在 Promise.All 中结合 promise 方法?

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

我有两个 promise 方法,第一个是GetInitialData ,它只会运行一次,还有一个名为ids的 10 个 id 的 Int 数组和第二个方法GetStudentName ,它将在每个学生 id 上执行。 现在我想在 Promise.All 中组合所有 11 种方法(方法 1 + 10 * 方法 2),我如何编写代码将 GetInitialData 与GetInitialData的 10 个实例组合到GetStudentName中的数组中,类似于以下?

Promise.All([GetInitialData + IDs.map(Id => GetStudentName(Id)]);

你在正确的道路上:

Promise.all([
  getInitialData,
  // you need to spread this one as it is an array of promises:
  ...ids.map(id => getStudentName(id),
]);

这是一个演示:
所有异步函数都被替换为在随机时间内解决的承诺

 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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