# 如何使用 async/await 实现 Promise.all 的效果
更多描述
如获取三个用户的信息,使用 Promise.all
的写法
const users = await Promise.all(getUser(1), getUser(2), getUser(3));
那如何不使用 Promise.all
实现以上效果
Issue
欢迎在 Gtihub Issue 中回答此问题: Issue 242 (opens new window)
Author
使用 async
/await
实现
const user1 = getUser(1);
const user2 = getUser(2);
const user3 = getUser(3);
const u1 = await user1;
const u2 = await user2;
const u3 = await user3;
Author
const all = (list) => {
const res = new Promise((resolve, reject) => {
let length = list && list.length
let count = 0
let result = []
if(!list || list.length === 0) {
resolve(result)
}
list.forEach(async (item, index) => {
try {
const res = await item
result[index] = res
count ++
if(count === length) {
resolve(result)
}
} catch(err) {
reject(err)
}
});
})
return res
}
使用
async
/await
实现const user1 = getUser(1); const user2 = getUser(2); const user3 = getUser(3); const u1 = await user1; const u2 = await user2; const u3 = await user3;
这个和上面的 Promise.all
并不一样吧。Promise.all
是并行操作,await
这个是串行操作
如获取三个用户的信息,使用
Promise.all
的写法const users = await Promise.all(getUser(1), getUser(2), getUser(3));
那如何不使用
Promise.all
实现以上效果
Promise.all 后面的参数为数组。。。
let req1 = () =>
fetch(
`https://github.com/shfshanyue/Daily-Question/issues?page=1&q=is%3Aissue+is%3Aopen`
);
let req2 = () =>
fetch(
`https://github.com/shfshanyue/Daily-Question/issues?page=2&q=is%3Aissue+is%3Aopen`
);
let req3 = () =>
fetch(
`https://github.com/shfshanyue/Daily-Question/issues?page=3&q=is%3Aissue+is%3Aopen`
);
// promise.all
const res = await Promise.all([req1(), req2(), req3()]);
const res1 = req1();
const res2 = req2();
const res3 = req3();
// await
const u1 = await res1;
const u2 = await res2;
const u3 = await res3;
所以这个题的答案是
tan90° 不存在
Author
看了一篇这个,好像可以 https://blog.csdn.net/github_38589282/article/details/79268484