繁体   English   中英

如何将promise中的一系列函数重构为循环

[英]How to refactor a series of functions in a promise to a loop

如何使用 for 循环重构此代码:

const [userA, userB, userC, userD] = await Promise.all([
    createTestUser(),
    createTestUser(),
    createTestUser(),
    createTestUser()
]);

你可以做

const userPromises = [];
for (let i=0; i<4; i++) {
   userPromises.push(createTestUser());
}
const users = await Promise.all(userPromises);
// const [userA, userB, userC, userD] = users;

或者,更短一点:

const users = await Promise.all(Array.from({length: 4}, _ => createTestUser()));

暂无
暂无

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

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